Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I know that transaction.atomic() is working
I am using with transaction.atomic and I am not convinced it is batching up The code is below #this gets the data to save\update writer = csv.writer(output) try: with transaction.atomic(): counter = 0 for row in csv.reader(input): get_record = MyModel.objects.get(ISBN=data_dict['ISBN'], source=data_source) get_record.name="new value" get_record.save() print counter counter = counter + 1 except IntegrityError: print "Something went wrong" class MyModel(models.Model): def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() try: save_this = super(ImportHcstock, self).save(*args, **kwargs) print "Saving ok" except: save_this = "fail" print "Saving fail" return save_this This saves the data correctly, however when I run it I see the counter value and 'Saving OK' next to each other when I would have expected to see the numbers without the phrase 'Saving OK' Am I miss understanding this? Thanks Grant -
Does IntegrityError in select_for_update() transaction is possible?
Let say I have code like this: with transaction.atomic(): my_objects = MyOjbect.objects.select_for_update().all() my_objects.update(...) Is there any possibility that IntegrityError exception will be raised in this transaction with locked objects? -
How to use a method on all elements, on the same field, in a model (Django)?
I am developing an app in Django. I have declared this model: class my_model(models.Model): field_1 = models.CharField(max_length=256, blank=True, null=True) field_2 = models.CharField(max_length=256, blank=True, null=True) field_3 = models.CharField(max_length=256, blank=True, null=True) I would like to replace the character sequence " " (double space) with " " (single space) in all the elements contained inside my_model, only on the Field_1. Here is how I would do it: def substitute_spaces(): rows = my_model.objects.all() for element in rows: if not pd.isnull(element.field_1): element.field_1.replace(" ", " ") element.save() Is there a quicker way to do it? -
Encode from Binary column and write them into text file
I am trying to read from database a binary column and then write the contents into file. I wrote the following code but i get the following error : UnicodeEncodeError: 'ascii' codec can't encode character '\xa0' in position 1015267: ordinal not in range(128) Below is my code: with open(getattr(settings,'DIR')+file+'.js', 'w') \ as filetowrite: filetowrite.write(str(bytes(col.data), 'utf-8')) -
Paginating DetailsView with certain condition in template Django
Please I need your assistance in the following scenario: I am filtering objects to display based on authenticated user and this prevent user from view other users data. Which means in my objects the pk may not be in sequence i.e object with id=1 would be for UserA and id=2 for UserB. My problem is on detailsview, I want UserA to view only his/her data while been able to paginate it. (Using object.get_next_by_FOO) would return 404 if the next item ID doesn't belong to the present logged in user (say UserA) I need to be able to display in details view all that belongs to UserA only while paginating it with next and previous. Which means I need a custom method to use in template. I have researched and found this SO question which is related to mine. But it didn't solve my problem using the code below. Please kindly help with a solution that might work. model snippet: class Results(models.Model): # user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) api_key = models.ForeignKey(ApiKey, on_delete=models.CASCADE) result_type = models.ForeignKey(ResultType, on_delete=models.CASCADE) note = models.CharField('Note', max_length=200, unique=True) viewed = models.BooleanField('Viewed', default=False) def others(self): return self.objects.filter(api_key__user=self.api_key.user).exclude(pk=self.pk) def this_type_previous(self): return self.others(pk__gt=self.pk).order_by('-pk')[0] def this_type_next(self): return self.others(pk__lt=self.pk).order_by('pk')[0] views snippet: class ResultDetailView(DetailView): template_name … -
Django - write helper for pagination
Both my list and pagination are loaded from ajax. My purpose is return pagination as text to adapt in one div. This is code to load list: accountlist = User.objects.all() paginator = Paginator(accountlist, 25) page = request.POST.get('page') lists = paginator.get_page(page) And pagination string : pagination = '<span class="step-links">' pagination += '<a class="first-page" data-page="1" href="#">&laquo; First</a>' pagination += '<a class="previous-page" href="#">Previous</a>' pagination += '</span>' pagination += '<span class="current">' pagination += 'Page '+str(lists.number)+' of '+str(lists.paginator.num_pages) pagination += '</span>' pagination += '<a class="next-page" href="#">Next</a>' pagination += '<a class="last-page" href="#">Last &raquo;</a>' I wonder that how able to create one helper.py to load pagination for all project. -
JWT Token expires before my setting value
In my Django Rest Framework, I use this solution. Login and refresh token functionality works fine with one exception. I set my expiration as 1800 seconds, but the token expires like 10 minutes. Here's my JWT_AUTH in settings.py: JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=1800), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', } I also added a refresh cycle for the token, which calls the refresh method once in 15 seconds; this also didn't change the result. What should I check for? Thank you. -
Using **dict as an argument in Django for create/update_or_create methods - Inconsistent Exceptions
I've a dict that looks like this: profile_data={'trial_duration': 0, 'tac_agreed': True, 'email': 'blahblah@gmail.com', 'signup_method': 'google', 'social_id': '2343432432', 'social_platform': 'google', 'name': 'blahblah tester'} I want to use the update_or_create method to map this dict to two different model objects. However, there seems to be some inconsistencies in how Django handles this. I have a model SocialInformation: class SocialInformation(models.Model): social_id = models.CharField(max_length=256, blank=True, null=True) social_platform = models.CharField(max_length=256, choices=SOCIAL_PLATFORM_CHOICES, default='', blank=True, null=True) When I use the following line, it executes with no exceptions and the values are mapped as expected, even tho most the items in the profile_data dict are not fields on the SocialInformation model, the mapping just ignores the irrelevant one and takes the relevant. social_info, created = SocialInformation.objects.update_or_create(defaults={**profile_data}) However, when I do the same thing for a different model, Profile: class Profile(models.Model): owner = models.OneToOneField('auth.User', primary_key=True, on_delete=models.CASCADE) name = EncryptedCharField(max_length=200, default='', blank=True, null=True) email = models.EmailField(blank=True) trial_duration = models.IntegerField(default=7) signup_method = models.CharField(max_length=256, choices=SINGUP_METHOD_CHOICES, default='', blank=True) etc. etc. If I execute the same line: profile, created = Profile.objects.update_or_create(owner=user, defaults={**profile_data}) I get the following error: FieldError: Invalid field name(s) for model Profile: 'social_id', 'social_platform'. Why does it not ignore the fields that are not on the Profile model like it does for … -
django migrations test: 'Manager' object has no attribute error
I'm testing a django migration inspired by this article. This method/ the MigrationTestCase works fine outside the user model, but seems to fall down when trying to access my custom user model. Here is the test method: from kapsule.tests.test_migrations import MigrationTestCase from django.db import connection from django.db.migrations.executor import MigrationExecutor from django.test.testcases import TransactionTestCase class MigrationTestCase(TransactionTestCase): """ A Test case for testing migrations """ # These must be defined by subclasses. migrate_from = None migrate_to = None def setUp(self): super(MigrationTestCase, self).setUp() self.executor = MigrationExecutor(connection) self.executor.migrate(self.migrate_from) def migrate_to_dest(self): self.executor.loader.build_graph() # reload. self.executor.migrate(self.migrate_to) @property def old_apps(self): return self.executor.loader.project_state(self.migrate_from).apps @property def new_apps(self): return self.executor.loader.project_state(self.migrate_to).apps class SummaryTestCase(MigrationTestCase): """ Test db migration """ migrate_from = [('accounts', '0003_subscription')] migrate_to = [('accounts', '0004_create_tokens')] def setup_before_migration(self): User = self.old_apps.get_model('accounts', 'CustomUser') demo_user = User.objects.create_user(email='contact@me.fr', # nosec password='ni likey no lightey', first_name='Contact', last_name='Me', company='Group', country='FR', ) Here is (a truncated version of) my user model (including my custom user manager): class CustomUserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): ... return user def create_user(self, email, password, **extra_fields): ... return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): ... return self._create_user(email, password, **extra_fields) class CustomUser(AbstractUser): """ Replace username by email as required and unique. """ # Hide username username = None # Overidde other … -
django-oauth-toolkit - provide application access to specific model
I have a concept of Slack's workspaces in my app and I'd like my consumers to specify to which "workspace" they are installing an app. Even though I can see that I can extend an Application model, it doesn't really help. Is there some best practise I could apply here? I've read the documentation several times. I was thinking of the following 2 workarounds, but there must be a simpler way for this. 1) First let user to authorise an app with his account and later let him to apply it to the workspace simply by creating some model and checking this on API/view layer. The problem here is that user experience is not as smooth as on Slack or Github where you select what entities you want an app to have access to when approving an app. 2) Extend Grant & Token models with a reference to a Workspace. In that case I'm struggling with adjusting forms, since I can not override them in a settings. (I can do that for models & templates). Do you maybe have some idea how to do this? Thank you -
Storing days off for user
I'm looking for good solution for storing days off for users. My app need to log when users will be available, so in User Model I want to create attribute where I will find all pick dates for days off (day off - mean user will be not available). I started from creating model for DayOff: class DayOff(models.Model): date = models.DateField() and add it to User model: class User(BaseUser): .... days_off = models.ManyToMany(DayOff) Maybe there is better solution? Cheers Fenrir -
TypeError: register_user() missing 1 required positional argument: 'request'
I have such problem with urlpatterns. I'm trying to answer for frontend a json file,but when i running a server, i got a typeerror, is it possible to test my code without HttpResponse or render? Here is my code urls.py from django.urls import path from backend.views import register_user urlpatterns = [ path(r'^register', register_user()), ] How should i construct my urls and json responses to run the server successfully views.py from backend.models import RegistrationForm, AuthenticationForm from backend.responses import Responses def register_user(request): if request.POST: form = RegistrationForm(data=request.POST) if form.is_valid(): user = form.save() name = form.cleaned_data['username'] surname = form.cleaned_data['surname'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = User.objects.create( first_name=name, last_name=surname, email=email, is_active=False ) user.set_password(password) send_account_activation_email(request, user) activate_user_account() return Responses.ok_response(301) else: form = RegistrationForm(data=request.POST) return Responses.ok_response(200) responses.py from django.http import JsonResponse class Responses: def error_response(self, error, text): comments = [{'success': False, 'error': {'code': error, 'message': text}}] return JsonResponse({'comments': comments}) def ok_response(self, code): comments = [{'success': True, 'code': code}] return JsonResponse({'comments': comments}) models.py class RegistrationForm(forms.Form): name_of_company = forms.CharField(label="Company name", max_length=30) country = forms.CharField(label="Country") city = forms.CharField(label="City/Town") '''logo_base64 = models.ImageField''' bio = forms.CharField(widget=forms.Textarea, label="Description") email = forms.CharField(widget=forms.EmailInput, label="Email", max_length=150) password = forms.CharField(label="Password", max_length=32) check_password = forms.CharField(label="Repeat password", max_length=32) -
How to Front end with backend in django
I am new to the programming my fronend desing is reday but i dont have isea how should i connect my front end with backend.my front end is desing using html css and javascript and backend is django -
Django runserver error- frozen importlib._bootstrap
I have been working on a project, and whenever I try the code:py manage.py runserver I get the error bellow. Kindly help to go about the error. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' -
Common 404 & 500 Page for My Django Project having multiple application
I'm developing one Django project which contains multiple apps. I want a common 404 and 500 error page for all the applications. How should i do it? I've implemented individual error pages for each app & It's working fine. But I want a common page which should be placed in my main project folder. -
How to make input box work in the result page
I am learning Django and i learn on making small project for lEARNING PURPOSE. I learned how work with input and use as variable. Now i want to use search box with the same principle. Please see the link of input based : https://stackoverflow.com/questions/58813945/changing-form-to-search-box index.html is the input after inserting info and clicking ok it directs to index2.html which shows the results What I need to change besides POST to GET to make it work as it works with input function? do i need to change form, models? My concern also i want to inset search bar in the navigation in index2.html where user can make search from the result page. This is my index2.html page. I tried to put {{form.as_p }} inside the form function but it does not work. I want after putting infro in search box and clicking search glyphicon (which does not work) will stay on the same page index2.html <!DOCTYPE html> {% load bootstrap4 %} {% load staticfiles %} <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro&display=swap" rel="stylesheet"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static 'main/css/master.css' %}"> </head> <body> <nav class='navbar mynav-fixed-top navbar-expand-lg bg-dark' role='navigation' id='navbar'> … -
How to get the array from HTML file into views file
How to get an array which contains a dynamic table's cell data in HTML file into Django views file for doing some calculations..Is it possible.... pls help me -
DRF not supporting multiple renderer_classes
I'm using Django 2.x and DRF I have a view which returns the binary data in different formats like pdf, eps, etc. To return binary response, I have set the renderer_classes property and my view is class DownloadQRCode(APIView): renderer_classes = (PdfFileRenderer, EPSRenderer,) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) name = serializer.validated_data.get('name') data = serializer.validated_data.get('data') mimetype = None if data and name: imgarr = name.rsplit('.', 1) if len(imgarr) == 2: name, format = imgarr if format == 'pdf': data = str(unquote(data, encoding='utf-8')) data, mimetype = generate_data_cairo(data, format) if format == 'eps': data = str(unquote(data, encoding='utf-8')) data, mimetype = svg_2_eps(data) if data and mimetype: response = Response(data=data, content_type=mimetype) response['Content-Disposition'] = 'attachment; filename=%s' % "-".join(name.split()) return response else: return Response(status=status.HTTP_400_BAD_REQUEST, data='Either data or mime type was missing') else: return Response(status=status.HTTP_400_BAD_REQUEST, data='filename does not contain formatInfo') else: return Response(status=status.HTTP_400_BAD_REQUEST) I have two renderer_classes PdfFileRenderer class PdfFileRenderer(BaseRenderer): media_type = 'application/octet-stream' format = None charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data and EPSRenderer class EPSRenderer(BaseRenderer): media_type = 'image/eps' format = None charset = 'utf-8' render_style = 'binary' def render(self, data, accepted_media_type=None, renderer_context=None): return data Using any one of them is working fine for that file type. But I want … -
How to configure Django and G Suite for SMTP
When the user is registering on my website an E-Mail is sent to the user to confirm his/her E-Mail. It works with this settings: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'abcdefghiklmnopq' EMAIL_PORT = 587 Now I want to switch to noreply@mydomain.com. I created an account on G Suite and made the following configurations: Comprehensive mail storage (Locally applied) Ensure that a copy of all sent and received mail is stored in associated users' mailboxes: ON SMTP relay service (Locally applied) ms_mail Allowed senders: Only addresses in my domains Only accept mail from the specified IP addresses: No Require SMTP Authentication: Yes Require TLS encryption: Yes Less secure apps (Locally applied) Allow Users to manage their access to less secure apps Less Secure Apps Allow less secure apps: ON Than I created an App Password an tried a lot of configurations like this: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'noreply@mydomain.com' EMAIL_HOST_PASSWORD = 'abcdefghiklmnopq' DEFAULT_FROM_EMAIL = 'noreply@mydomain.com' SERVER_EMAIL = 'noreply@mydomain.com' EMAIL_PORT = 465 I can't find a good documentation on Google or Django how to configure the settings. Does anybody now a good resource? Is the App Password/Less secure Apps the right way to do … -
Python Password Reset
here is my password reset routes path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), when i submit email from the form it goes auto to password reset done instead of generating an error that password_reset_confirm template not found , the dbconnection error not coming up also. please help -
how to extract fields from pdf in python using pdfminer
I have a pdf form that I need to extract email id, name of the person and other information like skills, city, etc..how can I do that using pdfminer3. please find attached sample of pdf -
Django query set complex order - union destroy order
I am new to Python and Django. I have a list of items. Each item has 2 fields: start_date and update_date. I am trying to query the items with the following order: If start_date > today, order by start_date and than by update_date Else (start_date <= today), order by update_date and than by start_date I end up with the following query: today = date.today() all = m.items.objects.annotate(updated_at_date=TruncDate('updated_date')) upcoming = all.filter(start__gte=today).order_by('start_date', '-updated_date') started = all.filter(start__lt=today).order_by('-updated_date', 'start_date') queryset = upcoming.union(started) But when I print the results, I get it in different order. However, if I return only upcoming or only started, I get good ordering. I think that Union destroy my ordering. What is wrong in my query? How can I fix that? -
Django: Getting 404 Error While Attempting to Use Slug in URL
I am a beginner learning Django through building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. When I go to http://127.0.0.1:8000/index, I see this page: When I click on Samsung, I see this page: Up to this is fine. But when I click on any phone model, like Galaxy S10, I get 404 error. It looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/details/galaxy-s10 Raised by: PhoneReview.views.ReviewView No review found matching the query You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 error. Here are my codes of models.py located inside PhoneReview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=150, null=True, blank=True) def __str__(self): … -
use more that one abstract/common models in other django models
I have a situation like this: class master1(models.Model): contacts = ... description = ... class master2(models.Model): contacts = ... class master3(models.Model): description = ... I have some attributes and methods that are used in some models. for example description is used in master1 and master3 but not in master2. on the other hands contacts are used in master1, master2. So I can't create an abstract model and just inherit from them. I want to have two separate models like this: class DescriptionMixin: description = ... class ContactsMixin: contacts = ... But inheriting from the proper model doesn't work for me. any idea? Note: this is just a simple representation of it, but you'll get the idea. thanks in advance -
How to embed images on a site django with dropbox?
Deployed a blog on Heroku. I upload the picture to the record through the admin panel on Dropbox via django-storages. The picture appears in the Dropbox application, but I don’t understand how to load the link to it. How to embed Dropbox pictures? You can advise other ways. While the idea is only to manually link links to the database ...