Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django manytomany user auto fill the user field
so what im trying to do is i have 2 tables in my models.py im trying to auto fill the user filed in the second table whatever user i select in my first table i tried to override the save_model in admins.py but didnt work here is my models.py file class Company(models.Model): company_name = models.CharField(max_length = 50) slug = models.SlugField(unique = True) user = models.ManyToManyField(User, related_name='company_user') objects = models.Manager() published = PublishedManager() def __str__(self): return self.company_name class Group(models.Model): company_name = models.ForeignKey(Company, related_name = 'co_name', on_delete=models.CASCADE) count = models.CharField(max_length = 50) real_count = models.CharField(max_length = 50) entry_date = models.DateTimeField() exit_date = models.DateTimeField() code = models.CharField(max_length = 10) code_date = models.DateTimeField() manifest = models.ImageField(upload_to='manifest/%m/%y', blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user = models.ManyToManyField(User, related_name='group_user', blank=True) objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-code_date',) def __str__(self): return str(self.id) my admins.py file @admin.register(Group) class GroupAdmin(admin.ModelAdmin): list_display = ['id', 'company_name', 'code', 'code_date', 'count', 'real_count', 'entry_date', 'exit_date', 'manifest', 'created' ] autocomplete_fields = ('user',) @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): list_display = ['company_name'] autocomplete_fields = ('user',) prepopulated_fields = {'slug': ('company_name',)} im trying to get the user in the Company class to be auto inserted in my Group class any advice -
Django and multi tenancy, data sharing
I'm working on a small project (CRM) using Django and I'm using Django-tenant-schemas, so each user have his own Schema, I would like to know how can I share some data between users ( ex: share user contact list between two users) I was thinking to create a table in the public schema but I don't think is the right solution since I'm isolating data -
How to use the data about objects modifications in Django?
Django stores a history of the modification for every object, it is something we can access to through the Django admin: It contains data about when the object was created/modified, the user who performed the action and the timestamp of the action: By giving a look at the database, I can guess this data is stored in a default table called django_admin_log: I am wondering if we can make use of this data in any way through the instance of a model ? I got used to adding manually my timestamps on every models through an Abstract Base Class, but I am wondering if it is useful in any way ? Or this table records only the modification taking place in the Django admin panel, which would makes the custom timestamp still needed for when the models instance were to be updated outside it. -
Original exception text was: 'QuerySet' object has no attribute 'customer_name'
Please check me this error with serializers. I have two model Customer and Factor: models.py: class Customer(models.Model): customer_name = models.CharField(max_length=120 ,verbose_name='بنام') final_price = models.DecimalField(max_digits=20, decimal_places=0, default=0, verbose_name='مبلغ کل فاکتور') def __str__(self): return f'{self.customer_name}' class Factor(models.Model): title = models.CharField(max_length=120 ,verbose_name='صورتحساب') name = models.ForeignKey(Customer,on_delete=models.CASCADE,verbose_name='بنام' ,related_name='factor_set') description = models.CharField(max_length=200 ,verbose_name='شرح کالا') price = models.DecimalField(max_digits=20, decimal_places=0, default=0.0,verbose_name='قیمت واحد') count =models.DecimalField(max_digits=20,decimal_places=0, default=1,verbose_name='تعداد') date = models.DateTimeField(default=datetime.datetime.now,null=True,verbose_name='تاریخ') def __str__(self): return f'{self.name}' serializer.py: class FactorModelSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField(many=True) class Meta: model = Factor fields = '__all__' class CustomerModelSerializer(serializers.ModelSerializer): factor_set=FactorModelSerializer(many=True) class Meta: model = Customer fields = '__all__' views.py: class GetAllData__(APIView): def get(self,request): query = Customer.objects.all() serializer=CustomerModelSerializer(query) return Response(serializer.data ,status=status.HTTP_200_OK) urls.py : from factor.views import GetAllData,GetAllData__ urlpatterns = [ path('get-all-data--', GetAllData__.as_view()), ] error : AttributeError at /get-all-data-- Got AttributeError when attempting to get a value for field customer_name on serializer CustomerModelSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'customer_name'. -
What is a good way to store guest user information that may be saved to a permanent user after registration in django?
I have a RESTful django webapp that allows users to take quizzes in a progressive system where the quizzes become increasingly difficult. Their progress is saved when they answer a question. I'm using django-rest-framework. class User(AbstractUser): pass class IntervalsProfile(models.Model): # Belongs to User model in 1-to-1 relationship # If User is deleted, then the corresponding IntervalsProfile will be deleted as well user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) level = models.IntegerField(default=0) current_level = models.IntegerField(default=0) # Level the user is currently viewing/on I would like users to be able to play as a guest, and if they so choose, register in order to save their progress. I cannot figure out how to save this guest information or how to save it once they register. I've searched thoroughly and all the solutions I see are either several years old or seem too cumbersome (such as adding a check for authentication in every view and having 2 cases for each view). Any advice or guidance would be much appreciated. -
Open and validate files to Django (Wagtail) admin before upload
thanks in advance, I'm currently trying to create some data types which are pretty much just Wagtail's default document type (implemented on the admin similar to Django's FileField) with a custom clean (validation) method. However, the problem I'm getting is when I'm uploading the file, I get an IOError when my program tries to open the file to process. Validating the extension is easy enough, but the problem lies when I actually have to open the file. I'm guessing when I try to open it the document isn't uploaded on the server yet when it tries to validate all the information, so opening it would be impossible. I wasn't able to find any information identifying whether this is even possible, and this seemed like a core Django constraint, not just Wagtail. P.S. I'm intentionally not showing code because it doesn't really clear to much up, but if you'd like to see it I'd be happy to provide it or anything else. -
create an api rest from django project and use it in flutter app
Hello am new in django and flutter .I'm working in a new project with this technologies and using firebase as a database: actually I have an ocr code in django that recognize the names of medecines : def ocr_title(im): image = cv2.imread(im, 0) img = cv2.resize(image, (500, 500)) img = cv2.GaussianBlur(img, (5, 5), 0) img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 4) himg, wimg = img.shape maxw = 0 text = '' title = pytesseract.image_to_data(img, config='--psm 6 --oem 3') for x, b in enumerate(title.splitlines()): if x != 0: b = b.split() if len(b) == 12 and len(b[11]) >= 4: if (int(b[8]) > maxw): maxh = int(b[9]) maxx = int(b[6]) maxy = int(b[7]) maxw = int(b[8]) text = b[11] #remove symboles from text text = re.sub(r'[^\w]', '', text) text = str(text) return (text) so my question is how can I create an API rest from this Django project so I can use these functions in a flutter -
How to override verification email function in dj-rest-auth and all-auth?
I want to override the email verification method and put it in a Celery queue as it takes up quite some time (2-3 seconds) for the email to send. My question is, where can I find the function with sends the email? -
Use value of text field in same HTML file
I want to use the value of input text of name='t0' in the same HTML file. Here is the code - <!DOCTYPE html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>Insert Account</title> </head> <body> <form action="{% url 'account_select' %}" method="GET"> <div class="text-center"> Id: <input type="text" name="t0"><br> <div class="one"> <button type="submit" class="btn btn-outline-primary" name="b1" value="Select">Select</button> </div> </div> </form> </body> </html> I want to use the value inserted in <input type="text" name="t0"> in place of "HERE" <form action="{% url 'account_select' "HERE" %}" method="GET"> Value has to be used in same HTML file because it will be directed to the the link. -
I want a storage for my django project but all the platforms that provide it require credit card details [closed]
Want storaje for django media but all the platforms that provide it require credit card details like AWS,google cloud storage,etc. is there any alternative to it?? -
django - DecimalField max_digits, decimal_places explained
So I'm just starting out with Django and using it to store forex prices which are represented as 1.21242, 1.20641, etc... model.py from django.db import models # Create your models here. class ForexPrice(models.Model): openPrice = models.DecimalField(max_digits=6, decimal_places=6) highPrice = models.DecimalField(max_digits=6, decimal_places=6) lowPrice = models.DecimalField(max_digits=6, decimal_places=6) closePrice = models.DecimalField(max_digits=6, decimal_places=6) My Question Is: How do the max_decimal and decimal_places attributes work? I'm using 6 for both fields assuming max_digits=6 will allow values to be stored up to 6 digits ie: 123456.000000 while decimal_palces=6 will support values up to 000000.123456. Is this assumption correct or am I missing something? Getting the following error when I save the record to the DB: A field with precision 6, scale 6 must round to an absolute value less than 1. -
Django-cms admin url 404 after language change
I recently started learning Django & Django CMS, and was trying to change the language of my website from English to Dutch, I migrated over my pages using Page.objects.filter(languages='en-us').update(languages='en') Title.objects.filter(language='en-us').update(language='en') CMSPlugin.objects.filter(language='en-us').update(language='en') In my settings.py I also changed LANGUAGE_CODE to 'nl' and set my languages and CMS languages as follows LANGUAGES = ( ## Customize this ('nl', 'Nederlands'), ) CMS_LANGUAGES = { ## Customize this 1: [ { 'code': 'nl', 'name': 'Nederlands', 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, ], 'default': { 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, } This works like a charm for the normal pages, but as soon as I try to open the admin interface I get the following error Request Method: GET Request URL: http://localhost:8000/nl/en/admin/cms/page/?language=en Raised by: cms.views.details Using the URLconf defined in PinManagementSite.urls, Django tried these URL patterns, in this order: sitemap.xml nl/ admin/ nl/ ^cms_login/$ [name='cms_login'] nl/ ^cms_wizard/ nl/ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] nl/ ^$ [name='pages-root'] ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, /nl/en/admin/cms/page/, didn't match any of these. As far as I can see I configured it all correctly, but when I go to the admin pages it tries to route me through /nl/en instead of just /nl/ and I can't figure out why. For completeness … -
Access a field's custom class in Django's ModelForm
I'm working on a ModelForm in Django that uses a Model, which has a custom CharField. When handling form errors I want to show the user valid examples (I thought this shouldn't be part of the raised ValidationError). However, when I try to access the fields using myform.fields by getting the invalid fields and the corresponding error messages using myform.errors.items() type(myform.fields["myfield"]) returns <class 'django.forms.fields.CharField'> instead of my custom MyField. Therefore myform.fields["myfield"].test() raises AttributeError: 'CharField' object has no attribute 'test'. How do I get the correct MyField instance from form.fields? class MyField(models.CharField): pass class MyModel(models.Model): myfield = MyField(max_length=20) class MyForm(forms.ModelForm): class Meta: exclude = tuple() model = MyModel myform = MyForm() print(type(myform.fields["myfield"])) -
please i'm doing a django project and i keep getting this on my browser
AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.8 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: C:\Users\iyiol\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\middleware\clickjacking.py, line 26, in process_response Python Executable: C:\Users\iyiol\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\iyiol\blog', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\iyiol\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\iyiol\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\lib\site-packages'] Server time: Wed, 28 Apr 2021 16:26:40 +0000 -
Django and get user locations
My question is can I get every user location and display it on map and if I could do it which framework support this with django -
Adding CSS to Django template email
I am using Django rest framework, want to send an email to user. html_message = render_to_string('emails/activate.html', {'email': email, 'role': role}) mail_template = strip_tags(html_message) send_mail( 'Activate your account', mail_template, 'sender', [email], fail_silently=False, ) return Response({'message': 'Activation email sent to ' + email},200) It works and I sent to my HTML file however it doesn't see any CSS and render it very badly. This is an example template I want to send. <!DOCTYPE html> <html lang="en" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <meta charset="utf-8"> <meta name="x-apple-disable-message-reformatting"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="format-detection" content="telephone=no, date=no, address=no, email=no"> <!--[if mso]> <xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml> <style> td,th,div,p,a,h1,h2,h3,h4,h5,h6 {font-family: "Segoe UI", sans-serif; mso-line-height-rule: exactly;} </style> <![endif]--> <title>Verify Email Address</title> <link href="https://fonts.googleapis.com/css?family=Montserrat:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet" media="screen"> <style> .hover-underline:hover { text-decoration: underline !important; } @keyframes spin { to { transform: rotate(360deg); } } @keyframes ping { 75%, 100% { transform: scale(2); opacity: 0; } } @keyframes pulse { 50% { opacity: .5; } } @keyframes bounce { 0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(0.8, 0, 1, 1); } 50% { transform: none; animation-timing-function: cubic-bezier(0, 0, 0.2, 1); } } @media (max-width: 600px) { .sm-leading-32 { line-height: 32px !important; } .sm-px-24 { padding-left: 24px !important; padding-right: 24px !important; } .sm-py-32 { padding-top: 32px !important; … -
Request can only be served after Gunicorn Worker Timeout and new Worker is booted
I have a Django application in Docker using Gunicorn to run the web server. If I request any URL, say app.com/dashboard, the page loads for 30 seconds. The reason it loads for 30 seconds is because that's how long the Gunicorn web worker to timeout, exit, and boot a new worker with a new pid. This is what shows up in the logs after a request and waiting for the worker to timeout. web_1 | [2021-04-28 17:51:57 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) web_1 | [2021-04-28 12:51:57 -0500] [7] [INFO] Worker exiting (pid: 7) web_1 | [2021-04-28 17:51:57 +0000] [9] [INFO] Booting worker with pid: 9 Once the new worker is booted, the page is served instantly. Has anyone experienced something similar to this before? -
Result type from cursor.fetchall() is list of tuples, but doc shows tuple of tuples
from django.db import connection conn = connection.cursor() conn.execute("some select query..") print( conn.fetchall() ) This shows that result from cursor.fetchall() is list of tuples, though in docs there is example: >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2"); >>> cursor.fetchall() ((54360982, None), (54360880, None)) That shows that result is not list, but tuple of tuples. Little bit confused, What I'm missing here? Thanks -
Guys help can any one please tell the best framework for web development [closed]
iam so confused about choosing the best and easiest framework for web development . i want expert brother to give me advices as a beginner. And I what is the best RDMS sql or MySQL thanks -
Can't get attribute 'DeprecationDict' on <module 'sklearn.utils.deprecation' from
enter image description here Can't get attribute 'DeprecationDict' on <module 'sklearn.utils.deprecation' from 'C:\Users\xyzxy\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\utils\deprecation.py'> -
DJango use templates from seperrate AWS S3 Bucket
I have a Django server running in an elastic beanstalk environment. I would like to have it render HTML templates pulled from a separate AWS S3 Bucket. I am using the Django-storages library, which lets me use static and media files from the bucket, but I can't figure out how to get it to render templates. The reasoning for doing it like this is that once my site is running, I would like to be able to add these HTML templates without having to redeploy the entire site. Thank you -
Apache httpd and Easy Apache 4 (Installing mod_wsgi for python app)
It's been a while but I am running into an issue and could not find any answers elsewhere. I pay for a dedicated server that is running Easy Apache 4 with Centos 7. I have root access to everything so no limitations. I am in the process of deploying a Python/Django app on the server for a client. When trying to install mod_wsgi it errors out stating it needs the package httpd-mmn. I can install the httpd module using yum but I am worried about conflicts since the server is using Easy Apache 4. Is this a relevant concern? I have a bunch of php sites on my server and I am afraid I'll break it. For the record, I do not want to use the experimental easy apache mod wsgi as it's, well...experimental and a use at your own risk situation. Any thoughts or recommendations would be great. -
Pinax announcement not showing for all users?
I have successfully created an announcement by the superuser account but the announcement won't display for all uses? Why so? -
todo list editable in django admin
i want to create todo editable only by admins in django admin interface. But i don't know how to do it personally for every user. i.e Every user should have a personal todo with checkboxes created in admin panel (the same checkboxes but for each user their own todo) I have created models but this is not what i want class CustomUser(AbstractBaseUser, PermissionsMixin): ... todo = models.ForeignKey(TodoList, null=True, on_delete=models.CASCADE) class TodoList(models.Model): title = models.CharField(max_length=128) class CheckBox(models.Model): title = models.CharField(max_length=128) is_complete = models.BooleanField(default=False) checkbox = models.ForeignKey(TodoList, related_name='todo', default=None, null=True, on_delete=models.CASCADE) -
Error binding parameter 1 - probably unsupported type django
I am trying to take the https path for an image from a csv file, download and store it in a CloudinaryField I tried r.content (it content the byte of the image) but CloudinaryField don't know,tried r.raw too nothing. If there is a best way to do that let me know thanks. this is the model class ArticleUnite(models.Model): libelle = models.CharField(max_length=255) image= CloudinaryField('image', overwrite=True, resource_type="image", transformation={"quality": "auto:eco"}, format="jpg", blank=True, null=True) image2 = CloudinaryField('image', overwrite=True, resource_type="image", transformation={"quality": "auto:eco"}, format="jpg", blank=True, null=True) reference = models.CharField(max_length=255,blank=True, null=True) description = models.CharField(max_length=255,blank=True, null=True) auteur = models.CharField(max_length=255, blank=True, null=True,default="sans auteur") prix_unitaire_article = models.IntegerField(default=1500) is_livre = models.BooleanField(default=False) is_cahier = models.BooleanField(default=False) is_accessoire = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.libelle) this is the code where I download the file then trying to store it in the database but that gives me an error binding #print(df['prix']) for x in df.index: #print(type(df.loc[x,'prix'])) c = float((df.loc[x,'prix'])) #cent = 700 #ct = float(cent) #print(ct) #print(c) if c < 999.0: print("<999") print(c*1000) price = int(c*1000) print(price) print(df.loc[x,'titre']) if df.loc[x,'is_livre']: cat_livr = CatalogueLivre.objects.get(libelle="livres") print(cat_livr) r = requests.get(df.loc[x, 'img'], stream=True) if r.status_code == 200: r.raw.decode_content = True print(type(r)) with tempfile.NamedTemporaryFile(mode="wb") as f: for chunk in r.iter_content(): f.write(chunk) print(f.name) …