Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting an smtp authentication with Django on PythonAnywhere
If you go on my webapp. You'll see a reset password option at the bottom of the login form but you need to register an account first and then try resetting your password. If you then type in your email and send, you will get a 500 Error page which I added custom styling to. So there was an error in my app in production, which does not show up in development. Everything worked perfect when I ran the localhost and tried it. I hosted my Django app on pythonanywhere so I went on my profile on PythonAnywhere and went to my log files and found this: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials m67sm7365001qkf.98 - gsmtp') 2020-10-10 08:08:56,103: OK: /password-reset/ Traceback (most recent call last): File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/contrib/auth/views.py", line 222, in dispatch return super().dispatch(*args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) … -
Changing ordering of model in the admin views
I have a User model in Django, in which I defined class Meta with ordering. It's defined like this: class Meta: verbose_name = _('user') verbose_name_plural = _('users') ordering = ('-speedy_net_site_profile__last_visit',) swappable = 'AUTH_USER_MODEL' But, I have two apps - Speedy Net and Speedy Match, and in Speedy Match I want a different order ( ordering = ('-speedy_match_site_profile__last_visit',) ). How can I do this? -
What is the appropriate way to use a ModelForm field as an argument to upload_to?
I have a ModelForm, where two of the fields are lastname and firstname. As several files are being uploaded by many different people, I would like to group the files into a directory based on their names. I've been trying to use a custom formatted string to do this, but so far I'm getting an error that there are not enough arguments for format string, and I am wondering if it as something to do with the form not being saved yet. My attempt to generate a filename based on form fields is: def filename_path(instance, filename): return os.path.join('applicant_documents/%s_%s/%s' % instance.last_name, instance.first_name, filename) and the field from my model is defined as: documents = models.FileField(upload_to=filename_path) Am I doing something wrong, or is this not possible? -
For what is better Django and for what Wordpress?
I asked this question because I would like to have an answer from a person with experience in that field. If something in my question is "wrong-formulated" tell me. (I know that Django and Wordpress are different thing, for this reason I'd want to know more) -
How to let PIL's Image.open find files from static?
I want to access a file in static from a module called "generate.py" inside my app. However I don't really have any idea how to do it. I believe I've properly "installed" the app because i can access the .html file in the App Things I've tried in generate.py 1 - from django.conf.urls.static import static Image.Open(static('resources/App/template/photothatiwanttoopen.jpg')) Error I get from code above: 'list' object has no attribute 'read' 2 - from django.conf import settings Image.Open(settings.STATIC_URL+'resources/App/template/photothatiwanttoopen.jpg') Error I get from code above: [Errno 2] No such file or directory: '/static/resources/App/template/photothatiwanttoopen.jpg' Here's my folder structure view - Project - App - templates - App - app.html - apps.py - generate.py <<< Script - models.py - urls.py - views.py - Project - settings.py and stuffs - static - resources - App - template - photothatiwanttoopen.jpg - manage.py and stuffs Here's last few lines of my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Let me know if you need any more information. -
Google App Engine Resource Error on the Django Deployment Tutorial
I have been looking for a great way to deploy my Django application and a Found Google App Engine Flex a pretty good solution. I have not much experience in application deployment so I follow along with the (Official Google Tutorial about the deployment. On the last step, the tutorial instructs me to deploy the application within the cmd prompt: gcloud app deploy. I follow along. Everything seems fine until I get this message: Updating service [default] (this may take several minutes)... After a while I get this message: Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [13] Flex operation projects/keen-opus-292007/regions/us-east1/operations/98cb5ea1-6231-40dc-a6e7-d44ddac73f77 error [INTERNAL]: An internal error occurred while processing task /app-engine-flex/insert_flex_deployment/flex_create_resources>2020-10-10T07:36:04.734Z7747.ue.0: Deployment Manager operation keen-opus-292007/operation-1602315365254-5b14c1e2a05d7-340fb934-bf85bfd7 errors: [code: "RESOURCE_ERROR" location: "/deployments/aef-default-20201010t093403/resources/aef-default-20201010t093403" message: "{\"ResourceType\":\"compute.beta.regionAutoscaler\",\"ResourceErrorCode\":\"403\",\"ResourceErrorMessage\":{\"code\":403,\"message\":\"The caller does not have permission\",\"status\":\"PERMISSION_DENIED\",\"statusMessage\":\"Forbidden\",\"requestPath\":\"https://compute.googleapis.com/compute/beta/projects/keen-opus-292007/regions/us-east1/autoscalers\",\"httpMethod\":\"POST\"}}" ] Every time I rerun the command gcloud app deploy I get the exact same error. Any idea how to fix that? Google Search doesn't reveal anything for me. -
Django Shopify Integration
I'm planning to create a dashboard in Django. I want to extract data from Shopify Database and integrate it to my Django app. For example, I want to get the customer's info in Shopify and Show it automatically to my Django app. How am I going to do this ? -
How to set user.id as username and password in django?
I want to set user id as username as well as password at a time of user registration in django. How can I do it ? -
How can do for-loop like this
How can I do for-loop like this in Django? list = ['AAA', 'BBB', 'CCC'] ========================================== {% for x in len(list), for y in list %} <p>{{x}}: {{y}}</p> {% endfor %} -
Shortcut to set all the fields in serializers to 'required=False'?
sorry if its duplicate, but I am not able to find the solution. Is there any way to set all the fields in serializers as required=False in one line, rather than declaring each field and explicitly write required=False for each field ? -
Unable to run django project due to error in manage.py file
I am working on django project. My python version is 2.7.15 and django version is 1.11.29. When I am trying to execute python manage.py runserver I am getting error as follows - File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax to solve this I removed from exc and run again then it throws error as follows - Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 13, in main "Couldn't import Django. Are you sure it's installed and " 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? May be the similar questions already available on stackoverflow itself but these solutions are not working in my case hence I am asking wrt my problem. Please suggest me how to resolve it? Thanks in advance. -
Django OperationalError: no such column: blog_post.slug
I'm a newbie of Django development. I have to create a blog, when I want to show the blog list, I got an error below. I guess that 'slug' column is not be created before I have the first migrations. And I re-migrate again, but it still has the same problem. Here are my code scripts: Thanks for your help! This is the error: -
How to send HTML in email using Django?
i am New in Django. i want to send html via Email using django. i am using following Code send_mail( 'Email Title', 'My Message', 'webmaster@localhost', [to mail], fail_silently=False, ) This Code is Sending simple strings,not sending HTML. for example if i pass <h1>test</h1> in my message body then it will return same. i want to apply <h1> tag in 'test'. How to do that ? -
Python equivalent of uidai ekyc authentication java implementaion
I'm implementing the Uidai Aadhaar verification process in python Django. I have the java code for the same. I tried to implement some functions. But I don't know how to implement the encryption and some other kinds of stuff. How to implement the exact code in python? ''' public class AuthAUADataCreator { public static final int AES_KEY_SIZE = 128; public static final int GCM_NONCE_LENGTH = 12; public static final int GCM_TAG_LENGTH = 16; private static final String JCE_PROVIDER = "BC"; private static final String ASYMMETRIC_ALGO = "RSA/ECB/PKCS1Padding"; private static final String ALGO = "AES/GCM/NoPadding"; private static final int SYMMETRIC_KEY_SIZE = 256; public static final int AUTH_TAG_BIT_LENGTH = 128; private static final String CERTIFICATE_TYPE = "X.509"; private PublicKey publicKey; private Date certExpiryDate; private String certPath; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS"); String otptxn = this.dateFormat.format(new Date()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String time = this.sdf.format(new Date()); File certificatePath = null; File DualcertificatePath = null; static { Security.addProvider(new BouncyCastleProvider()); } public AuthAUADataCreator() { } public AuthAUADataCreator(InputStream publicKeyFileName) { InputStream fileInputStream = null; try { CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE, JCE_PROVIDER); fileInputStream = publicKeyFileName; X509Certificate cert = (X509Certificate) certFactory.generateCertificate(fileInputStream); this.publicKey = cert.getPublicKey(); this.certExpiryDate = cert.getNotAfter(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not … -
how can I use django channels for background tasks
I am seeing that people are using celery in django for background tasks. But i want to know that is there any way to do background tasks in django with django-channels so please tell me how do i do it. -
Django 404: Uploaded images to admin page in prod not reflected on blog
Now this was working smoothly in dev, but I keep getting the Error 404 in my apache2 prod machine while uploading images from the Django admin page. I see the images get added to my /media/images/ folder from the admin upload, but it fails to load on the website. Is this a permission issue? This is my folder structure within /var/www/: app |_app |_media |_images |_file.png |_static This is my settings.py specification for media: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/') This is my urls.py specification: urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [..] (Note: Please request further info in the comments, will keep adding on as-need basis) -
integerity error in django(i think its about that new foregn key)
im have post model and a profile model on profile model i have a OneToOneField this is my profile model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): GENDER_CHOICES = [('boy', 'پسر'), ('girl', 'دختر'), ('i prefer not to say', 'ترجیح میدهم نگویم')] user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='profile_pictures', blank=True, default='default.jpg') name = models.CharField(max_length=30) age = models.IntegerField(default="0") birth_day = models.CharField(max_length=30)#DateField(blank=True) gender = models.CharField(max_length=20, choices=GENDER_CHOICES) address = models.CharField(max_length=30, blank=True, default="---") bio = models.TextField(max_length=300, blank=True, default="---") phone = models.IntegerField(blank=True, null=True) skills = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorites = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_books = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_movies = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_musics = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_sports = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") and this is my post model: from django.db import models # from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from taggit.managers import TaggableManager from user.models import Profile class Post(models.Model): STATUS_CHOICES = [('published', 'published'), ('draft', 'draft')] title = models.CharField(max_length=60) slug = models.CharField(max_length=120, unique=True) image = models.ImageField(blank=True, upload_to="posts_images", null=True) image_alt = models.CharField(max_length=35, blank=True, null=True) body = models.TextField() date = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') author = models.ForeignKey(Profile, on_delete=models.CASCADE) tags … -
Django Web API Call Server Pagination Issue
So I am trying to make a call on an API endpoint that could return results to a template in the range of 0 - 450,000 items. The API has a search endpoint as so, https://api.rawg.io/api/games?search=rimworld, and since this only results in 12 games, there's only one page and my function works as expected. When there are more than 20 results, the max allowed per page for this API (RAWG.IO API). This results in the JSON having a "next" key with something like this, https://api.rawg.io/api/games?page=2&search=grand. I cannot for the life of me figure out how to get the data from any of the pages past page 1. I have resorted to using JS to write this function, but I much rather use a Django view. I run into the same issues, where I can't collect past the first page. Whenever there is more than one page, my memory usage skyrockets, the page doesn't show any results, and the loading icon runs forever. There's either a memory leak or the resulting dict that I'm storing these in to display is just that huge. Whether someone can give me some insight in either JS or Python, I'm sure I can figure out … -
sorting of queryset with direction in django rest framework
Request from client side(tabulator) come with query param 'filters[0][value]' for filtering and 'filters[0][dir]' for direction, filtering works but sorting doesn't. Following are my code class UserSerializerView(generics.ListAPIView): model = User serializer_class = UserSerializer pagination_class = CustomPagination filter_backends = [filters.OrderingFilter] ordering_fields = ['username', 'email', 'is_approved'] ordering = ['username', 'email', 'is_approved'] def get_queryset(self): queryset = User.objects.exclude(is_staff=True) names = self.request.query_params.get('filters[0][value]', None) if names: queryset = queryset.filter( Q(username__icontains=names) | Q(first_name__icontains=names) | Q(last_name__icontains=names)) return queryset -
Django prefetch_relatad with ManyToMany field
I have this two models im my django application (latest version). class Company(models.Model): trade_name = models.CharField(....) focal = models.ManyToManyField(Focal) class Focal(models.Model): name = models.CharField(....) Django automaticaly created a third table to conect the models: company_focal. I want to implement the prefetch_related in the admin queryset. I`ve been trying something like this, but it didnt worked well. def get_queryset(self, request): queryset = super(FocalAdmin, self).get_queryset(request) return queryset.prefetch_related('company') How to correctly do it? -
Unable to access Media files in django template
I am trying store a set of files manually in media folder and access them through path in a template. Here goes my settings for media MEDIA_URL="/media/" MEDIA_ROOT=os.path.join(BASE_DIR,"media") Here is my project urls urlpatterns = [ path('admin/', admin.site.urls), path('',include('books.urls')), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Here goes my template code <div class="category-img"> <img src="/media/logo.png" alt=""> </div> And there is no image displayed .Media folder has logo.png file in it.I got following error. Internal Server Error: /media/bordered.jpg/ Traceback (most recent call last): File "C:\Users\Sriram\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Sriram\anaconda3\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sriram\Desktop\books_site\books\views.py", line 42, in bookinfo book["description"]=descriptions[zonar][books[zonar].index(book_name)] KeyError: 'media' -
Could not resolve URL for hyperlinked relationship using view name "book-detail"
Previously I was using ModelSerializer and there were no error. When I replaced it with HyperlinkedModelSerializer this error was thrown Could not resolve URL for hyperlinked relationship using view name "book detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. this is serializers.py file: class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Book fields = ['id', 'url', 'title', 'subtitle', 'isbn'] model.py class Book(models.Model): title = models.CharField(max_length=250) subtitle = models.CharField(max_length=250) author = models.CharField(max_length=100) isbn = models.CharField(max_length=13) def __str__(self): return self.title views.py class BookListView(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer and urls.py router = routers.DefaultRouter() router.register('books', BookListView) app_name = "books" urlpatterns = [ path('', include(router.urls)), ] view name book-detail doesn't exist in my views, probably Django created it automatically and I don't know where to find and debug it? Thank you. -
How to install Pillow in Django can anyone help me by step to step. i am using mac os 10.15 catalina
i am getting error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-install-w34kt0to/pillow/setup.py'"'"'; file='"'"'/private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-install-w34kt0to/pillow/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-record-sun2k_so/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/Pillow cwd: /private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-install-w34kt0to/pillow/ Complete output (172 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.9 creating build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpoImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageMode.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PngImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/XbmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PcxImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SunImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/TarIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FitsStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpegImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/BdfFontFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GribStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageStat.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PixarImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageColor.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ContainerIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MspImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MicImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/_version.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImtImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GifImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PalmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageQt.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageMath.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PaletteFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FontFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PdfParser.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ExifTags.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageCms.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FpxImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageChops.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/BufrStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PSDraw.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PcdImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageFilter.py … -
django this is not working.. image is not showing in the page
I am trying to make simple webpage but I am unable to load the image in the page <div class="background_image" style="background-image:url({% static 'static/images/home_slider.jpg'%})"></div> -
Django Oscar version updated automatically
I am learning about Django Oscar. I was following a tutorial yesterday that is using Django Oscar version 1.6. I followed all the instructions in the tutorial. It was working fine yesterday. Now, when I ran my project today using python manage.py runserver, I got the error about using get_core_apps which has been removed in Django Oscar 2. I ran pip freeze to see the version of Django Oscar installed on my device and it said 2.0.2. Was it updated automatically? I did not make any changes to the project since working on it yesterday.