Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run multiple instances of a Django app?
This question doesn't involve any code. I just want to know a way to run multiple instances of a django app and if it is really possible in the first place. I make django apps and host them on Apache. With the apps, I noticed a conflict between multiple users accessing the web app. Let us assume it is a web scraping app. If one user visits the app and run the scraper, the other user accessing the site from a different location doesn't seem to be able to visit the app or run the scraper unless the scraping that the first user started finishes. Is it really possibe to make it independent for all different users accessing the app? Please suggest! Thanks -
django tinymce display issue
I installed tinymce in my django admin in order to beh able to insert code/videos etc in my questions on my quiz-app. But, when I go to display the questions, it appears in code, like if in my tinymce tool I write "c", in the question displayed it will be as follow in the pic: quiz/admins.py from django.contrib import admin from .models import Questions from tinymce.widgets import TinyMCE from django.db import models # Register your models here. class QuestionsAdmin(admin.ModelAdmin): fields = [ 'question', 'optiona', 'optionb', ] formfield_overrides = { models.TextField: {'widget': TinyMCE()}, } admin.site.register(Questions, QuestionsAdmin) quiz/models.py from django.db import models from django.conf import settings # Create your models here. class Questions(models.Model): CAT_CHOICES = ( ('datascience', 'DataScience'), ('productowner', 'ProductOwner'), ('businessanalyst', 'BusinessAnalyst'), #('sports','Sports'), #('movies','Movies'), #('maths','Maths'), #('generalknowledge','GeneralKnowledge'), ) question = models.TextField(max_length = 850) optiona = models.TextField(max_length = 800) optionb = models.TextField(max_length = 800) optionc = models.TextField(max_length = 800) optiond = models.TextField(max_length = 800) answer = models.TextField(max_length = 850) catagory = models.TextField(max_length=20, choices = CAT_CHOICES) class Meta: ordering = ('-catagory',) def __str__(self): return self.question piattaforma/settings.py TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen … -
Reverse for '____' with no arguments not found?
my project error is: NoReverseMatch at / Reverse for 'post_new' with no arguments not found. 1 pattern(s) tried: ['$post/new/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_new' with no arguments not found. 1 pattern(s) tried: ['$post/new/$'] Exception Location: k:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: k:\ProgramData\Anaconda3\python.exe Python Version: 3.7.4 in base.html : 22 <ul class="nav navbar-nav"> 23 <li><a class="navbar-brand bigbrand" href="{% url 'blog:post_list' %}">My Blog</a></li> 24 <li><a class="navbar-link" href="#">About</a></li> 25 <li><a class="navbar-link" href="http:www.google.com">Google</a></li> 26 <li><a class="navbar-link" href="http:www.github.com">Github</a></li> 27 </ul> 28 <ul class="nav navbar-nav navbar-right"> 29 {% if user.is_authenticated %} 30 <li> 31 <a href="{% url 'blog:post_new' %}">New Post</a> 32 </li> 33 <li> 34 <a href="{% url 'blog:post_draft_list' %}">Draft</a> 35 </li> 36 <li> 37 <a href="{% url 'blog:logout' %}">Logout</a> 38 </li> 39 <li> 40 <a>Welcome {{ user.username }}</a> 41 </li>``` -
IntelliJ profiling Django application
I am developing a Django application inside IntelliJ. Now, I would like to profile it. To see, if some code is run more than it should if some queries are slow,... All I can find is : That exist debug tool that shows DB profile Link Python profiler (like vmprof): I did install vmprof and I run it. But my problem is, that all code inside all libraries is showed,... I can't find my code inside.. is there a way to configure to show only my code? -
Email sent to wrong account
Ive built an contact form which sends an email. I'm just having a bit of trouble in relation to the account its being sent to. I want the email to be sent from "servwishes@gmail.com" to the "Contact_Email". Right now the email is going from "Contact_Email" to "servwishes@gmail.com". my views.py looks like this: def contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') template = get_template('users/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['servwishes@gmail.com'], headers = { 'Reply To': contact_email } ) email.send() return render(request, 'users/contact.html', {'form':Contact_Form }) And my setting.py looks like: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'servwishes@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Django how to capture user data
I currently have a 3 x 3 grid of images, displaying a total of 9 images. The sourced images from 3 different folders(representing 3 different categories). Code for this is in the file random_image.py template to display the images is in pickfeel.html The interface looks like this: I want the user to click on an image and press the 'Next' button. When the 'Next' button is pressed it will record the following data: username Category of selected image What should I do implement this? P.S: I'm inexperienced with Django and any help would be greatly appreciated random_Image.py @register.simple_tag def random_images_category1(count=3): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/normal/' path = '/app_pickfeel/static/app_pickfeel/images/normal/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] print(random.sample(files, count)) return [rand_dir + filename for filename in random.sample(files, count)] @register.simple_tag def random_images_category2(count=9): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/mania/' path = '/app_pickfeel/static/app_pickfeel/images/mania/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] print(random.sample(files, count)) return [rand_dir + filename for filename in random.sample(files, count)] @register.simple_tag def random_images_category3(count=9): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/depression/' path = '/app_pickfeel/static/app_pickfeel/images/depression/' files = [f for f in os.listdir(settings.BASE_DIR + path) if … -
badly formed hexadecimal UUID string in django?
I have a Django version 3.0.5. I have a UUID uuid.uuid4 as a primary key and migrate to tables the in Mysql engine. after migrate I have import the data which present in the SQL lite database. now I have import all the data to Mysql and logged in Django admin I get the error like this badly formed hexadecimal UUID string mymodel.py # # Create your models here. class ChallansModal(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False, unique=True) code = models.CharField(max_length=255,verbose_name='Codes') Date = models.DateField(verbose_name='Date') def __unicode__(self): return self.ID def __str__(self): return self.ID thank you for the contributions -
How can I show related model property in Django admin?
I have two models, Retailer and Product like this: class Retailer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) website = models.CharField(max_length=255) description = models.TextField(default=None, null=True) def __str__(self): return str(self.id) class Product(models.Model): id = models.AutoField(primary_key=True) price = models.IntegerField(default=None, null=True) retailer = models.ForeignKey(Retailer,on_delete=models.CASCADE,related_name='products') is_active = models.BooleanField(default=False) def __str__(self): return str(self.retailer) + ' - ' + str(self.price) Now what I get is this: But what I want is showing Retailer name instead of Retailer id in Django admin, what should I do? -
-bash: manage.py: command not found while trying to run a git project
I am trying for the first time to run the project from the git. Here is the link to the project: https://github.com/spilab-umich/phishing-warning-experiment I followed all the suggested steps to deploy a Django on a host and it worked fine. I run: python manage.py runserver and after that wanted to come to the importing mail module,typing: python manage.py makemigrations mail I get the error message: -bash: manage.py: command not found Have anyone idea what I am doing wrong? How can I resolve this error? -
What is the best way to get a list of favorite articles by tags for a given user in django
I have a question. Lets say we have the following models: model User: pass model Article: text, ... tags = ManyToMany(Tag) model Tag: id, name, ... model Visits: hour = Integer(number of hours since epoch) article = ForeignKey(article) counter = IntegerField() In my client's local storage I have an array with the client's favorite tags. My question is: What would be the best way to query articles with the following criteria: The first ones to appear should be those who are related to the client's favorite Tags Then, There should be the rest of articles, without repeating the favorite ones Respectively, they should be ordered by "hot value", which is a summatory of the 24 latest models' counter related to each article I've put on my thinking cap for DAYS trying to come up with an efficien solution, but the best I've achieved takes entire seconds to query with a dataset of 10. Please, help. Also, off-topic, have I used correctly the expression "put on (one's) thinking cap"? English ain't my main languaje and I'm still learning! -
Do I need to place __ini__.py in each directory in a directory tree leading to my class?
I'm building a Django project with Python 3.6. I have created this directory structure ... project - commons - util - __init__.py - my_class.py The contents of init.py are from . import my_class In another class, I attempt to import my MyClass like this from commons.util import MyClass but I'm getting this error ModuleNotFoundError: No module named 'commons' Am I creating my init.py properly? -
Model Not showing in Django Admin created using built in AbstractUser
I have created a custom user model using Django built in User and I have added my own fields. When I try to run the code I am getting error. I have searched everywhere and I am not getting the answer to this error. I have run the code with empty admin.py it worked perfectly for LogIn/Logout and SignUp But nothing my showing in Django admin. Then after some research I came with the code mentioned below but Still I am getting error! models.py from django.db import models from django.contrib.auth.models import BaseUserManager,AbstractBaseUser class MyAccountManager(BaseUserManager): def create_user(self, email, username, address,phone_number,password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, address=address, phone_number=phone_number, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, address,phone_number,password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, address=address, phone_number=phone_number, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="email",max_length=60,unique=True) username= models.CharField(max_length=30,unique=True) phone_number= models.IntegerField() address=models.CharField(max_length=300) is_active=models.BooleanField(default=True) is_admin=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','address','phone_number'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True forms.py from django.contrib.auth import get_user_model from … -
How can I get the current app's verbose name as a context variable in all templates in Django?
My django project has an app. The app's folder is main_menu_app. I didn't want to always have to type something like: {% url 'main_menu_app:PAGE' %} in templates, but rather {% url 'main_menu:PAGE' %} so inside my mysite/urls.py, I have this: path('main_menu/', decorator_include(login_required, ('main_menu_app.urls', 'main_menu'))), This names my app "main_menu". This works great in most cases. Unfortunately, recently, I acquired a need for adding the current app's verbose name to every template as a context variable. I can do this with a context processor, and normally, you can resolve the app you are in by doing: request.resolver_match.app_name unfortunately, mine resolves to "main_menu", and when I try to grab an app_config with that name (which contains the verbose name), it can't find it: from django.apps import apps app_name = request.resolver_match.app_name apps.app_configs[app_name] # KeyError: 'main_menu' apps.app_configs OrderedDict([..., ('main_menu_app', <MainMenuAppConfig: main_menu_app>), ...]) Is there some way I can resolve what I get back from request.resolver_match to an app_config? I know I can hard-code the main_menu_app name, but I'd rather do it dynamically, so it always works for all apps. -
Django check user permissions in serializer
I have a serializer that I'm trying to show all the granted permissions to the user for a particular project. I have it working in the serializer under different fields, but when I try to add them all together in a new field called my_permissions I get a list of every possible permission. I think it has something to do with my utils script, but I can't seem to figure out the issue. Here is my serializer: class ProjectSerializer(LightWeightSerializer): id = Field() name = Field() slug = Field() description = Field() created_date = Field() modified_date = Field() owner = MethodField() members = MethodField() is_private = Field() role_permissions = MethodField() anon_permissions = Field() public_permissions = Field() i_am_member = MethodField() i_am_admin = MethodField() my_permissions = MethodField() def get_members(self, project): members = Membership.objects.filter(project_id=project.id).select_related() return MembershipSerializer(members, many=True, context=self.context).data def get_i_am_member(self, project): members_list = Membership.objects.filter(project_id=project.id).select_related('user') for member in members_list: if member.user == self.context['request'].user: return True return False def get_role_permissions(self, project): members_list = Membership.objects.filter(project_id=project.id).select_related('user') for member in members_list: if member.user == self.context['request'].user: return RoleSerializer(member.role).data['permissions'] return [] def get_i_am_owner(self, obj): if "request" in self.context: return is_project_owner(self.context["request"].user, obj) return False def get_i_am_admin(self, project): members_list = Membership.objects.filter(project_id=project.id).select_related('user') for member in members_list: if member.user == self.context['request'].user: if member.is_admin: return True … -
How to render a pdf file as pdf in browser using django
I am using Django web frame work. I am taking pdf files from users (notes/book/etc). Then I want to display those pdf in website, but I could not find a way. Methods that failed 1)iframe 2)simple rendering using django 3)pdf.js library. Also browser blocks rendering initially. Care to suggest a method and steps to implement it. -
Python: Convert string representative of a string array to a list
I am trying to convert a string representative of a string array containing double quotes, single quotes and commas in its array items in to a python list when that array is passed to an API endpoint over postman. (Im am using Python 3.6) Ex: value passed in postman "data":["bacsr "attd" and, fhhh'''","'gehh', uujf "hjjj"",",,,hhhhh,, ","1"] element 1 = "bacsr "attd" and, fhhh'''" element 2 = "'gehh', uujf "hjjj"" element 3 = ",,,hhhhh,, " element 4 = "1" What I tried and failed: post_values = request.data['data'] post_values = ast.literal_eval(post_values) Gives this error: During handling of the above exception (invalid syntax (, line 1)), another exception occurred: How can I convert this in to a 4 element list with relevant string escapes? -
How to have PyCharm suggest code completion for Django
I have the following code: from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase) def test_newUserEmailNormalized(self): email = "test@TEST.COM" user = get_user_model().objects.create_user(email, 'test123') I want PyCharm to suggest autocompletion on the last line when I write get_user_model(). but it only suggests main, not, par. And when I write get_user_model().objects. I want it to suggest auto-completion options including create_user but it doesn't suggest anything. How do I enable PyCharm to help me with autocompletion here? These are my AutoCompletion settings: -
DRF - Route to Obtain Token
What is the best way to create route to obtain a token? I want a browsable API. urls.py router = routers.DefaultRouter() router.register(r'tokens', views.TokenViewSet) views.py class TokenViewSet(viewsets.ViewSet): queryset = Token.objects.all() serializer_class = AuthTokenSerializer def create(self, request): serializer = AuthTokenSerializer(data=request.POST) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) This solution works, but don't return actions in OPTIONS. -
Django communication of api from one app to another app
I am working on a Django project Example: I have a model in app 'A', named UserBooks I wrote API in views for sending all the Books owned by an User in the format of JsonResponse Hence I am able to use it as a Simple Json Response and test it in Postman Now my problem is, in app 'B', I have user_books.html template When I access a particular Url which will call the user_books view, I have to access data from API of app 'A' for UserBooks which is JsonResponse, now I have to convert it into dictionary or again convert that data to Model that we have earlier and then pass it to the template to render the data into that view I am looking for a solution that will be easy for this process Here's the details about the project It has two apps -> A, B In app 'A' I wrote models and API's In app 'B' I wrote views that will map data from API of app 'A' I want to use app 'A' for accessing API which gives responses in Json format But in app 'B' all the views are connected to templates and … -
why django signal not working with custom User model?
I am creating a Django signup form through User model and UserCreationForm and customized the User model to accommodate single user defined field contact. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class SignUp(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Contact = models.TextField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: SignUp.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import SignUp class SignUpForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) # phone = format() class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class CustomSignUpPage(forms.ModelForm): Contact = forms.CharField(max_length=10) class Meta: model = SignUp fields = ('Contact', ) views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages #from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm, CustomSignUpPage def home(request): return render(request, 'authenticate\home.html', {}) def login_user(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ('login success')) return redirect('home') else: messages.success(request, ('error while login, please try again')) return redirect('login') else: return render(request, … -
How to get datetimefield as string in django queryset's values_list() function?
I have a model which contains a datetime field. I need to write the rows from that model table to excel sheet. As the model field is datetime field, when writing to the excel, it's writing a number like 45976 etc for dates instead of 2020-04-01 as string. I'm getting values of rows using queryset.values_list(*fields_to_fetch) This fields_to_fetch contains the datetimefield I'm looking for. When I print the type, it is saying DateTimeField in the console. Is there any way to get the datetimefield as string type? I was able to convert each item in the values_list() to list and then the datetimefield into string and append it to a new list and write to excel. I'm looking for a way to avoid all this. -
How do I remove to_field from django model?
I have a model like this: class MyModel(models.Model): field_1 = models.ForeignKey(User, related_name='some_name', to_field='unique_id') # more fields In this I want to remove my to_field from field_1, but when I did this, I got error while migrating. django.db.utils.DataError: (1265, "Data truncated for column 'field_1' at row 1") I think the cause of problem is that unique_id is string while my primary key is int, and data already stored in my db is unique_id, which I want to change to id. Is there any good way to achieve this? -
Django Wizard Form problems
I have multiple page form, and i want in to add this feature (course.tutor.add(request.user)(Here course is my model and tutor is field in it) to the view class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) form_list = (CourseForm1,CourseForm2,CourseForm3,CourseForm4) def done(self, form_list, **kwargs): instance = Course() for form in form_list: for field, value in form.cleaned_data.items(): setattr(instance, field, value) instance.save() return redirect('courses:my_courses',username=self.request.user.username) I want to add same feature to my function. I did needed row in capital def create_group(request): group_form = GroupForm() if request.method == 'POST': group_form = GroupForm(request.POST,request.FILES) if group_form.is_valid(): new_group = group_form.save() NEW_GROUP.ADMINS.ADD(REQUEST.USER) new_group.subscribers.add(request.user) return redirect(new_group.get_absolute_url()) else: group_form = GroupForm() return render(request,'groups/create_group.html',{'group_form':group_form}) -
slug 404 not found in django
Here is my views.py from .models import Post,Author def posts_list(request): all_posts = Post.objects.all() context = { 'all_posts': all_posts } return render(request,"post_list.html",context) def posts_detail(request, slug): unique_post = get_object_or_404(Post, slug=slug) context = { 'post': unique_post, } return render(request,"posts_detail.html",context) and my urls.py is: from django.urls import path from posts import views urlpatterns = [ path('admin/', admin.site.urls), path('post/',views.posts_list), path('post/(<slug:slug>/', views.posts_detail,name='post'), ] every time i go to http://127.0.0.1:8000/post/first i get 404 page not found i tired reloading my django server and find others solution too but i cannot figure out what the problem upto https://http://127.0.0.1:8000/post the route is working but after slug not working please help me to solve this issue. -
Django Taggit: how to add tags as listed annotation to queryset.values()
I'm having some conceptual difficulty with understanding how to annotate a queryset for objects which have an attribute of "tags" as defined in the django-taggit library: class MyObject(models.Model): ... tags = TaggableManager(blank=True, verbose_name="Tags") When querying for this object, I want a .values() list, but for some reason...the tags field is not there...I'd ideally like to .annotate() my queryset with a list of the tag names: e.g., instance['tags'] = ['tag1', 'tag2']... Has anyone achieved this before?