Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - python 3.8 any url obfuscate packages available?
Working with django and Python 3.8 for url obfuscation, however no python packages available for the same. The following py packages are not supported by python 3.8: url-obfuscate # link: https://pypi.org/project/url-obfuscate/ django-unfriendly # link: django-unfriendly Please suggest any url obfuscation packages. -
How to create custom list field in serializer, which contains another serializer(model), django rest framework?
I need to use a list of one model serializer in another, I have tried use SerializerMethodField() but didn't succeed. So i have following codes: models.py class TyresGroup(models.Model): code = models.CharField("Наименование группы колес", max_length=50) brand = models.CharField("Бренд", max_length=50) class Meta: verbose_name = "Группа колёс" verbose_name_plural = "Группы колёс" def get_image_filename(instance, filename): code = instance.tyres_group.code slug = slugify(code) return "post_images/%s-%s" % (slug, filename) class Images(models.Model): tyres_group = models.ForeignKey(TyresGroup, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename, verbose_name='Image') class Meta: verbose_name = "Фотография" verbose_name_plural = "Фотографии" class Tyre(models.Model): group = models.ForeignKey(TyresGroup, blank=True, on_delete=models.CASCADE) images = models.ManyToManyField(Images, related_name='tyresgroup', blank=True) type = models.CharField("Тип колеса", max_length=2, choices=TYRE_TYPES) code = models.CharField("Код протектора", max_length=10) title = models.CharField("Название", max_length=30) width = models.CharField('Ширина', max_length=5, choices=WIDTH) height = models.CharField('Высота', max_length=5, choices=HEIGHT) radius = models.CharField('Радиус', max_length=5, choices=RADIUS) speed_index = models.IntegerField('Индекс скорости') tread_depth = models.IntegerField('Глубина протектора') standard = models.FloatField('Какой-то стандарт') oa_dia = models.IntegerField("OA DIA") max_pressure = models.IntegerField('Максимальное давление(КРА/PSI)') certificate = models.CharField('Сертификат качества', max_length=5) distance = models.IntegerField("Преодолимая дистанция колёс") max_loading = models.IntegerField("Максимальная нагрузка") class Meta: verbose_name = "Колесо" verbose_name_plural = "Колёса" and serializers.py: class TyreSerializer(serializers.ModelSerializer): images = ImagesSerializer(many=True) class Meta: model = Tyre fields = '__all__' class TyresGroupSerializer(serializers.ModelSerializer): # tyres = serializers.SerializerMethodField() # def get_tyres(self, Tyre): # queryset = Tyre.objects.all() # return queryset.values() class Meta: model … -
I need help in creating a form for Django that Admin only can create
Hi I need some help in creating a Form that Admin can create. I'm still trying to work with the Forms page and I already created a form however it's giving me and Error. (1048, "Column 'user_type' cannot be null") How can I create a form when during creation I can choose which "user_type" I can assign the user. I tried the basic user creation and it's fine but I want it to be streamlined and more customized for future admin users. Here's my models.py: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, username, password=None, user_type=None, is_tester=False, is_senior_test_manager=False, is_superuser=False, is_pqa=False, is_staff=False, is_admin=False, is_test_lead=False, is_test_manager=False, is_active=True): if not username: raise ValueError("User must have a Username!") if not password: raise ValueError("User must have a Password!") user_obj = self.model( username=self.normalize_email(username) ) user_obj.set_password(password) user_obj.user_type = user_type user_obj.ad = is_admin user_obj.tm = is_test_manager user_obj.pqa = is_pqa user_obj.ts = is_staff user_obj.tl = is_test_lead user_obj.stm = is_senior_test_manager user_obj.superuser = is_superuser user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_pqa(self, username, password=None): user = self.create_user( username, password=password, is_pqa=True, user_type=1 ) return user def create_tester(self, username, password=None): user = self.create_user( username, password=password, is_staff=True, user_type=2 ) return user … -
How to override call_wrapper method in Django 1.9?
I am using Django 1.9 to expose SOAP 1.1 API with Spyne version 2.12.16 I need to implement logging for every request XML and response XML in my platform. Django urls.py is url(r'^your_data/', DjangoView.as_view( name="YourDataService", services=[YourDataService], tns='http://127.0.0.1:8000/', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())) views.py: from spyne.decorator import rpc from spyne.model.primitive import String, AnyDict from spyne.service import ServiceBase class YourDataService(ServiceBase): @rpc(String, String, String, _returns=AnyDict) def call_this_method(self, a, b, c): return {'aa': 'OK','bb': 'Great','cc': 'Perfect'} I read somewhere, overriding call_wrapper method of Spyne ServiceBase class can log request and response XML data for that service. But implementing the same resulted in weird logging etc issues: class ServiceBaseAbstract(ServiceBase): def call_wrapper(cls, ctx): try: return ctx.service_class.call_wrapper(ctx) except Exception as err: print err It gives an error: No handlers could be found for logger "spyne.application.server" API works fine without overriding call_wrapper. I am really confused and can't find a way out of this. Your help will be much appreciated. Thank you -
What language(s) should I use for my backend?
When I do research on the backend, I always see that there are multiple parts to it, such as the database, application, server... and see recommendations for different languages such as SQL or python. But do I really need different languages for the backend? For example, can Django(or any other backend language/library) handle all the main parts of the backend? And is PHP worth learning in 2020... -
adjust Data-table horizontal length in django template
I am using a Data-Table in my django template with zero configuration See here: Data-Table But it shrinks the table horizontally according to the content, I want it to keep it as the same size as the screen but unable to find any solution. Here's an image to simplify the question: Template: <script> $(document).ready(function () { $('#table_id').DataTable( ); }); </script> -
how to prevent html page reload in django
<html> <head> </head> <br> <body> <h2><center>Choose your pose</center></h2> <div><center> <datalist id="languages"> <option value="dancers-pose"> <option value="mountain-pose"> <option value="pranamasana"> <option value="tree-pose"> <option value="triangle-pose"> <option value="warrior-pose"> </datalist> <input type="text" id = "abc" list="languages"> <br> <br> </center> </div> <div> <center> <h2>Upload your image</h2> <form method='POST' enctype="multipart/form-data"> {% csrf_token %} <input type = "file" name="document"> <br> <button type = "submit">upload file</button> </center> </form> </div> <div> <center> <button type="button" onClick = "myFun()">Get Results</button> </center> </div> <script> function myFun(){ var try_pose = document.getElementById("abc").value; console.log(try_pose); try_pose1 = try_pose + ".jpg"; console.log(try_pose1); </script> </body> </html> Above is my html file def full(request): if(request.method == 'POST'): files = glob.glob('media/*') for f in files: os.remove(f) uploaded_file = request.FILES['document'] fs = FileSystemStorage() # uploaded_file.name = 'temp.jpg' fs.save(uploaded_file.name, uploaded_file) path = "media" + "/" + uploaded_file.name # im = Image.open("media/temp.jpg") im = Image.open(path) im = im.resize((620,620)) width, height = im.size im= im.save("media/temp.jpg") return render(request,'full.html') Above code is present in my views.py . When the image is submitted the data present in the textbox is lost may be because the page is reloaded. I request for a solution which might be a small change in the above code which would not reload the page so I can access the value of the textbox later … -
Django: Clean method not picking up the submitted file
General file processing in my form works fine (on save/edit). But I cannot get file information when I access the file in the clean/validation method. Can you please help :) forms.py class BatchForm(ModelForm): csv_file = FileField(label='CSV File') class Meta: model = Batch fields = ('project', 'name', 'csv_file', 'filename') def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(BatchForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() csv_file = cleaned_data.get("csv_file", False) print("file: ", csv_file) # csv_file prints None I tried printing csv_file but I got None as output My template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> </form> My view: def create_batch(request): form = BatchForm(request.POST or None, request=request.FILES) if form.is_valid(): form.save_batch(request=request, create_batch_flag=True) return redirect('list_batch_url') return render(request, template_name, {'form': form}) -
How to run background process code using django?
First time I worked django-background-task package. I tried to see the documentation and create a sample background task file. it's working fine. but schedule time and repeat time is not working I set interval time=10 seconds. but it runs every second how to fix it. I tried many ways still not getting a solution or any other alternate package use to perform background process My Code from django.shortcuts import render from django.http import HttpResponse from background_task import background # Create your views here. @background(schedule=5) def hello(): print("Hello World!") def index(request): hello(repeat=10) return HttpResponse('<h1>Hello World</h1>') In documentation given, we can override the schedule timing. How it works schedule=5 seconds and repeate=10 seconds anyone can explain how it works. how to fix this issue. -
Django development server command
I am little confuse about django developement server.Here question is if my project running based on gunicorn and ngnix in production environment. Should my local development need nginx for serving static files? if yes then what command should i use instead of Python manage.py runserver. Help me get out of it. -
How to run management command from django view.py
I want to run my custom command from django view which create new user. Here is my command python manage.py tenant_command createsuperuser --schema=schema_name Here schema name my be change Above command is same as python manage.py createsuperuser Here i didn't know how to pass username, email and password and confirm password any suggestion would be appreciated -
Django NoReverseMatch error in RedirectView
I have been attempting to make a follow feature for my site, however I am consistently getting stuck on errors. Here is the UserProfileInfo model slug = models.SlugField(unique=True,allow_unicode=True) # ... other fields def get_absolute_url(self): kwargs = { 'slug':self.user.username, } return reverse('mainapp:view_profile_with_pk',kwargs=kwargs) # return reverse('mainapp:post_list') def save(self, *args, **kwargs): self.slug = slugify(self.user.username) super().save(*args, **kwargs) Here is my view class AddFriendRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): slug = self.kwargs.get("slug") obj = get_object_or_404(UserProfileInfo,slug=slug) # user_profile = User.objects.get(username=username) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.friends.all(): obj.friends.remove(user) else: obj.friends.add(user) return url_ Here is my urls.py path('profile/<str:slug>/add/',views.AddFriendRedirect.as_view(),name='add_friend'), And finally here is my HTML <a id="new-post" href="{% url 'mainapp:add_friend' slug=username %}"> <button id=""> Connect </button> And here is my error NoReverseMatch at /mainapp/profile/don0024/add/ Reverse for 'view_profile_with_pk' with keyword arguments '{'slug': 'don0024'}' not found. 1 pattern(s) tried: ['mainapp/profile/(?P[^/]+)/$'] And the full traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/mainapp/profile/don0024/add/ Traceback: File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\views\generic\base.py" in get 188. url = self.get_redirect_url(*args, **kwargs) File "C:\Users\User\interests-site\interests\mainapp\views.py" … -
How to test EmailMessage .send() with backend modified by EmailBackend
How to test emails send via EmailMessage .send() when email backend is set by EmailBackend object? As the backend is modified inside this function mail.outbox does not store any outgoing emails. What would be the most Django way of approaching this? function in question: def send_email_to_users(email_message_obj): recipients = [user.email for user in email_message_obj.addressees.all()] ap = Admin_Profile.objects.get(id=1) backend = EmailBackend( host=ap.email_host, port=ap.email_port, username=ap.email_host_user, password=ap.email_host_password, use_tls=ap.email_use_tls, fail_silently=False) email = EmailMessage( subject=email_message_obj.title, body=email_message_obj.body, from_email=email_message_obj.email_from, to=recipients, connection=backend) email.send() test: class Testsend_email_to_users(TestCase): def setUp(self): User.objects.create_superuser( username='admin', email='jlennon@beatles.com', password='glassonion') @override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend') def test_one_email(self): '''should send one email''' Admin_Profile.objects.create( user=User.objects.all().first(), email_host=settings.TEST_EMAIL_HOST, email_port=settings.TEST_EMAIL_PORT, email_host_user=settings.TEST_EMAIL_HOST_USER, email_host_password=settings.TEST_EMAIL_HOST_PASSWORD, email_use_tls=True, ) u1 = mixer.blend(User, email=settings.ADMIN_EMAIL) email_message = Email_Message.objects.create( title='test title', body='test body', email_from=settings.TEST_EMAIL_HOST_USER, ) email_message.addressees.add(u1) send_email_to_users(email_message) # should send one email self.assertEqual(len(mail.outbox), 1) result of the test: > self.assertEqual(len(mail.outbox), 1) E AssertionError: 0 != 1 models.py: class Admin_Profile(models.Model): ... email_host = models.CharField(max_length=100, blank=True) email_port = models.IntegerField(null=True, blank=True) email_host_user = models.EmailField( max_length=70, null=True, blank=True) email_host_password = models.CharField(max_length=100, blank=True) email_use_tls = models.BooleanField(null=True, blank=True) class Email_Message(models.Model): title = models.CharField(max_length=78) body = models.TextField() email_from = models.EmailField() addressees = models.ManyToManyField(settings.AUTH_USER_MODEL) timestamp = models.DateTimeField(auto_now_add=True) ... Notes: send_email_to_users is functional and sends 'real' emails; test_settings.py contains: all other tests that use django.core.mail.send_mail pass the tests and are captured in mail.outbox; … -
What is good architecture for Django with a lot of table?
What is good architecture for Django with more than 60 table (Restful) is good to have an app as api and for each table has sub app in main app or not? -
django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known
My GitLabCI: stages: - test # jobs test_django: stage: test image: python:3.6 # this pulls the standard python 3.6 docker image services: - postgres:9.5 # this pulls a docker image with pgsql on it variables: # env vars made available to the script below CI_DEBUG_TRACE: "false" # set to false to reduce the debug output from the CI jobs POSTGRES_DB: "project_ci_test" POSTGRES_USER: "postgres" POSTGRES_PASSWORD: "" DATABASE_NAME: "$POSTGRES_DB" DATABASE_HOST: "postgres" # magically finds the service above DATABASE_USER: "postgres" DATABASE_PASSWORD: "" DJANGO_SECRET_KEY: "somerandombogusstringtokeepdjangohappyandstartingproperly" script: - apt-get update -qy - apt-get install -y python3-pip wkhtmltopdf xvfb # extra packages used for pdf rendering in the tests - pip install -r requirements.txt - pep8 . --filename=*.py --ignore=E128,E265,E501 --repeat - python manage.py migrate - python manage.py test But now i'm getting error while running migrations. GitlabCi Error: self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known ERROR: Job failed: exit code 1 Hello, guys could you please help me. what is wrong with my settings, it was working a few month ago but not it's not working. … -
Django Twilio API Custom Body Form
Using the code below, what is the best way to create a custom "body" for sending an SMS message using the Twilio API? to = '+11111111111' client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) response = client.messages.create( body='Hello, testing Twilio in Django', to=to, from_=settings.TWILIO_PHONE_NUMBER) -
Django : Invalid Token in cryptography.fernet
I am running a website using Django . Below is the error: raise InvalidSignature("Signature did not match digest.") cryptography.exceptions.InvalidSignature: Signature did not match digest During handling of the above exception, another exception occurred: raise InvalidToken cryptography.fernet.InvalidToken Below is the package: def _verify_signature(self, data): h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(data[:-32]) try: h.verify(data[-32:]) except InvalidSignature: raise InvalidToken hmac.py: def verify(self, signature): digest = self.finalize() if not constant_time.bytes_eq(digest, signature): raise InvalidSignature("Signature did not match digest.") What is the one i am missing? -
Global Exception Handling in Django-rest-framework
Is there a way to handle all the exceptions globally without using try-except block in django rest framework. I want to convert html error page that django is throwing to a customised json object response. -
AbstractUser Signup
Hello I am trying to extend Django User model using Abstract User but I get OperationalError when signing up My Profile model: class Profile(AbstractUser): email = models.EmailField(max_length=150) bio = models.TextField() university = models.CharField(max_length=30) def __str__(self): return self.username CREATED = 0 ACTIVE = 1 BANNED = 2 KICKED = 3 UPGRADE = 4 STS = ( (CREATED, 'Just Created'), (ACTIVE, 'Activated'), (BANNED, 'Disabled'), (KICKED, 'Disabled'), (UPGRADE, 'Active'), ) status = models.IntegerField(choices=STS, default=CREATED, blank=True, null=True) My Signup form: class SignUpForm(UserCreationForm): username = forms.CharField( label='', max_length=30, min_length=5, required=True, widget=forms.TextInput( attrs={ "placeholder": "Username", "class": "form-control" } ) ) first_name = forms.CharField( label='', max_length=50, min_length=2, required=True, widget=forms.TextInput( attrs={ "placeholder": "First name", "class": "form-control" } ) ) last_name = forms.CharField( label='', max_length=50, min_length=2, required=True, widget=forms.TextInput( attrs={ "placeholder": "Last name", "class": "form-control" } ) ) university = forms.CharField( label='', max_length=50, min_length=2, required=False, widget=forms.TextInput( attrs={ "placeholder": "University", "class": "form-control" } ) ) email = forms.EmailField( label='', max_length=255, required=True, widget=forms.EmailInput( attrs={ "placeholder": "Email", "class": "form-control" } ) ) password1 = forms.CharField( label='', max_length=30, min_length=8, required=True, widget=forms.PasswordInput( attrs={ "placeholder": "Password", "class": "form-control" } ) ) password2 = forms.CharField( label='', max_length=30, min_length=8, required=True, widget=forms.PasswordInput( attrs={ "placeholder": "Confirm Password", "class": "form-control" } ) ) class Meta: model = Profile fields = ('username', … -
How do I make a 404 error route to a Wagtail page?
When a 404 error is thrown in a project that uses Wagtail, I'd like to have the site redirect to a page in the CMS. How do I do this? I know Wagtail has a redirects feature, but that doesn't seem to do what I want; if I were to use that I'd need to have some kind of wildcard selector that would be superseded by more specific redirects. I searched around the issues but this was as close as I found. But that seems to be more related to admin 404s if I'm reading it right. -
how to deal with the order of input elements with the same name?
guys. I am new in using Django. In short, I want to collect data provided by users. For instance, I want to collect the scores of many subjects. Basically, I will design a div element containing two input element with these two name: subject_name and score. This design works fine if user upload a score at each post-request. Whatif a user want to upload many scores at one post-request? How can I support this operation? Assumes there is a add-button to add a new div element which contains the two same input elements. After user click the submit-button, the variable request.POST in Django will contain two lists which represents the subject and the score respectively. However, the order of the values inside these two list is not guaranteed, which is bad in accuracy. Any ideas? Thanks for your sharing. -
How to create a Doughnut chart in django admin interface using foreign key field data?
I am working on creating a Django admin interface, wherein i am plotting in three doughnut charts to visualize the data but out of three charts only one charts is working correctly. What i think the problem is that the other two charts are using the data of foreign key field and i am not sure how to make the call for the data. Following is my model.py, admin.py and template for creating the interface. Kindly help me to modify the code for the charts, the help will be highly appreciated. models.py admin.py Part Of Template -
Django Default HomePage Not Found
I have a Django project, and working correctly, but not display default home page. I know that, you have to add a url pattern to display , but this is not exactly what am I asking. Normally, if you create a Django project, Django will serve you a default web page something like that And you can change it by adding a url pattern for '/' in 'project.urls' like that : urlpatterns = [ ... url(r'^$', wellcomeView, name='wellcomeView'), ... ] But normally , Django must show this default home page while you don't change anything in url patterns or settings. So this is my question : I didn't change anything in settings or urls , but after a migration , it stopped to show default page. What thing can caused this ? This is my scenario : 1- I created a Django 2.2.7 project (Everything is ok) 2- Crated apps, models. But now views 3- Migrations, created db, test models. Still there is not any views, but shows default home page. 4- Changing models, again and again, and migrating every time. (But still no views , and not changing settings or urls, only looking up in default admin page. Also … -
How do I get rid of extra zeroes in django DecimalField?
I am using a DecimalField in my model as I need quite a few decimal places for some of the values. But for some of the values I don't need as many zeroes. The problem is in the same field I will have some values that are 0.76 and other values that are 0.0001548337258. Unfortunately FloatField is not accurate enough for my needs. But when I use: class Part(models.Model): dec_number = models.DecimalField(max_digits=19, decimal_places=15) I unfortunately get the same amount of empty 0's on my 0.76. I would like the output when I call that field to be 0.76 in that location, and 0.00000037. Currently my output is: 0.760000000000000 0.000154833725800 I am trying to get my output to be: 0.76 0.0001548337258 Is there a way to remedy this? -
Django rest api delete, returns 404 not found
I have this api, that's not deleting the items by id. Here is the model: class Contact(models.Model): pass user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('User'), related_name="user") #uid = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False) contact = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('Contact'), related_name="contact") created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) is_contact = models.BooleanField(default=False) objects = ContactManager() def __str__(self): return self.user.username and the serializers.py class ContactSerializer(ModelSerializer): class Meta: model = Contact fields = [ 'user', 'contact', 'is_contact', ] and Views.py class ContactDeleteAPIView(DestroyAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer lookup_field = 'id' permission_classes = [IsOwnerOrReadOnly] And urls.py: path('<int:id>/delete', ContactDeleteAPIView.as_view(), name='delete-contact'), This just returns 404 not found when I try to do a delete action. What am I missing?