Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add data to manyToManyField on form submission
I would like to automatically add the User who submitted the form to the users many to many field on the below-given model when the form submits, how could I do this from the view? The model: class Project(MainAbstractModel): users = models.ManyToManyField(User) title = models.CharField(max_length=25, default="Conflict") The view: def myconflicts(request): if request.method == "POST": form = ProjectForm(request.POST) if form.is_valid(): form.save() else: form = ProjectForm() return render(request, 'conflictmanagement/myconflicts.html') And my form is simply: class ProjectForm(ModelForm): class Meta: model = Project fields = ["title"] -
Django: ModuleNotFoundError: No module named 'sslserver'
I would like to use https for my Django development server using django-sslserver. I have installed it using $ pip install django-sslserver I have then added it to my settings.py INSTALLED APPS: INSTALLED_APPS = [ ... 'sslserver', ... ] However, if I now try to start the sslserver like this: python3 manage.py runssslerver 0.0.0.0:8080 I get the following error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/pi/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/pi/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/pi/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pi/.local/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/pi/.local/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sslserver' Any idea how to fix this? -
How to make boolean field hold only one True value in Django
Am working on a Saving scheme, i have implemented it so that it works on cycles. Is there a way i can have only one active cycle enforced by my boolean field? models.py class Cycle(models.Model): cycle_name = models.CharField( max_length=220, null=True, blank=True, unique=True) rate = models.IntegerField(default=15, null=True, blank=True) cycle_period_start = models.DateField(max_length=255, blank=False, null=False, unique=True) cycle_period_end = models.DateField(max_length=255, blank=False, null=False, unique=True) is_active = models.BooleanField(default=True) def __str__(self): return self.cycle_period_start.year + "/" + self.cycle_period_end.year Basically what i want is that when i add new cycle, the field is_active is set to False for other cycle. Thank you for the help -
Choosing a relationship between two tables (SQLAlchemy)
Consider two tables: User and Calculation. Calculation's structure: {“id”: <primary_key>, “array”: <array of numbers>, “calculations”: <array of all calculations for given array of numbers>} User creates those calculations. I want to be able to query for calculations associated with specific User. As far as I know, I need to have user reference on calculation model to do that. Question is: is it possible to avoid changing Calculation structure by having User reference on Calculation model? I was thinking about having an array field on User model with IDs of calculations. Is this a viable solution? -
What is Roadmap To Django Full Stack Developer
I want to be a full stack Django developer .I learned PYTHON HTML and CSS Bootstrap 4. What should I learn along with those. -
I cant send email with django
When I try to send an email with django this error appears: 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 b2sm12936529wrm.30 - gsmtp') -
Django, website unable to load media files
I have hosted Django website on server, it runs and loads static files. My Website have an option for users to upload files. Users can upload files but When it comes to display it does not show. It worked well in my local machine but I don't know what went wrong in production When I open image files in website in new tab it displays The requested resource was not found on this server. settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' -
Django AWS S3 Bucket contents won’t show in html website
I've set up an s3 bucket and tested it with my django app. I am able to upload photos via django admin to s3 as I saw it make a folder and upload the image file in it; however, the images doesn't display on the HTML page. Not even the default image that I've set was displayed (which was already uploaded in s3). I tried reading and watching some tutorials to check if I've missed something but so far I haven't found anything. What am I missing here? What other solution/s can I try? I had whitenoise set before but I already removed it from my settings.py. I'm new to django so did I miss a step or something? Here is my settings.py (I've set my debug to false in bash_profile): ... DEBUG = (os.environ.get('DEBUG_VALUE') == 'True') ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'crispy_forms', 'django_summernote', 'storages', ] ... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Here is my models.py (model for the images part): class Post(models.Model): title = models.CharField(max_length=255, unique=True) … -
Django using two Foreign Keys to the same model throws error despite using related_name
I'm trying to use two one-to-many links to the same model and getting the following error when running makemigrations: <class 'actionlog.admin.ActionInstanceInline'>: (admin.E202) 'actionlog.Action' has more than one ForeignKey to 'actionlog.Audit'. Searching shows this is a common problem resolved by using related name. However, this doesn't fix the error for me. Could someone show me what I'm missing? The models are: class Audit(models.Model): audit_ref = models.CharField(max_length=5) audit_name = models.CharField(max_length=40) lead_auditor = models.ForeignKey('LeadAuditor', on_delete=models.SET_NULL, null=True) class Action(models.Model): action_ref = models.CharField(max_length=3) audit_ref = models.ForeignKey('Audit', on_delete=models.CASCADE) lead_auditor = models.ForeignKey('Audit', on_delete=models.CASCADE, related_name='lead_auditors') Appreciate any help. Thanks -
Mousewheel scroll event up/down (mouse middle button pressed down) does not work on django
I've been working on my django website. It's a pretty basic one. I usually scroll down the page by holding the scrollwheel down but it doesn't work in my project. Before it worked fine when I was using just regular html/css/js but after implementing django to my project it stopped working. Any ideas how to fix this? -
why we use instance as second parameter instead first in Django forms for existing db entry
I see instance need to pass as second argument in the model forms to edit the existing entry of DB.. but why we are not passing it as first arg >>> from myapp.models import Article >>> from myapp.forms import ArticleForm # Create a form instance from POST data. >>> f = ArticleForm(request.POST) # Save a new Article object from the form's data. >>> new_article = f.save() # Create a form to edit an existing Article, but use # POST data to populate the form. >>> a = Article.objects.get(pk=1) >>> **f = ArticleForm(request.POST, instance=a)** >>> f.save() can you help me to understand this... !! TIA -
In Django, how do I properly update a field based on a counter in a different model (while avoiding race conditions)?
I have a model which I'm numbering starting at 1 per foreign key, exactly like the situation here: Django: Maintaining a counter in a field (race condition) So let's say that I want my User to have a list of Notes, and each Note would be numbered starting from 1 per User. In the linked question above, the accepted answer talked about locking the whole table due to the aggregate query, but I'm trying to see if there's a better approach than implementing some LockedAtomicTransaction (I feel that it may be additional complexity) and locking the entire table (due to performance concerns). So I'm thinking of using a field counter instead: class User(models.Model): ctr = models.IntegerField(default=0) class Note: user = models.ForeignKey(User) slug = models.IntegerField() # I'm using this numbering for "clean" referencing in the URL Then I would override the save() of Note. Let's say that the logged in user has been attached to the Note to be created in the view: def add_note(request): user = request.user if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.user = user note.save() Then: class Note(models.Model): # ... def save(self, *args, **kwargs): # Retrieve the user again, but locked this … -
generate Fake data and " AppRegistryNotReady: Apps aren't loaded yet" error
I want to generate fake data for my app in Admin panel,but I get below error . When I use python manage.py runserver the app execute but without fake data. I want to generate fake data by stand alone file (population.py) , but I get Error . There are some solution according this error in stackoverflow I check all post but don't solve my problem . **This is my error message ** File "population.py", line 14, in <module> from first_app.models import Topic, Webpage, AcsessRecord File "E:\Dropbox\CS\Project\Project\django\django_BC\django_pro\first_app\models.py", line 4, in <module> class Topic(models.Model): File "C:\ProgramData\Anaconda3\envs\dj1.11\lib\site-packages\django\db\models\base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "C:\ProgramData\Anaconda3\envs\dj1.11\lib\site-packages\django\apps\registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "C:\ProgramData\Anaconda3\envs\dj1.11\lib\site-packages\django\apps\registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. population.py file for generate fake data os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_pro.settings') import django # setup django according above setting django.setup from faker import Faker import random from first_app.models import Topic, Webpage, AcsessRecord # import fake module # create an objet from faker fakegen = Faker() # The main info is topic before import class of model that we crated # becuse we want to fill database similary model # We want to add random for topic from a list … -
How do I integrate http://www.daterangepicker.com/ with Django and postgres
Please explain how to integrate js widget http://www.daterangepicker.com/ with django and perform a search query by date with django forms -
What are the best frameworks/libraries in 2020 for Web scraping using Python
I want to build a we scraping application. I have think to use django-rest-framework for REST API and want to use Scrapy for Web scraping. I'm little bit confused i'm going to right way or not. So please provide some suggesting about that. That application will be as like e-commerce site analysis. Please provide me best suggesting from you. Thanks from me. -
How to structure hierarchy of apps in Django app
being new to Django (v3.x) I'm trying to write an IDE-like app that allows to: Create new "work projects" (not as in Django projects, but as in work projects like in an IDE, where each created work project later on contains various artefacts and files) always in the context of a project upload files to that project and then work with them. Hence, the structure of my Django app should look like so: myapp/ /project/ /file_1 /file_2 /file_3 Accordingly, following best practices of how to build URIs the URL patterns probably ultimately should look like: myapp/project/<int:project_pk>/file/<int:file_pk>/ What I don't fully understand is: How can I cause Django to always work in the context of a pre-selected project? Either I do it all in a stateless fashion where users always need to specify the full URL including the project primary key. Problem is that my templates may not know what primary key the current project has, which may cause issues with reverse URLs and the like. Or I somehow keep the current project primary key as state in some kind of non-global but shared variable among all resources in the same project. Here the problem is obviously how to invalidate the … -
How to solve two modul imports each other in Django
I have two models named as User and Newspaper. User can be author or reader and both are in the same model. So Newspaper has an author and it can create many newspapers. Reader has favorites and he can add as many newspapers as he want. Question: How to solve circular import between two modules? Extra info: user and newspaper are two different apps. ├── project │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── newspaper │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── user ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── tests.py └── views.py newspaper/models.py class NewsPaper(models.Model): title = models.CharField(max_length=255) file = models.FileField(upload_to=get_file_upload_path) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="created_newspaper") created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title[:20] + '...' if len(self.title) > 20 else self.title user/models.py class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField(max_length=20, unique=True, validators=[validate_phone_number]) firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) favorites = models.ForeignKey(NewsPaper, on_delete=models.CASCADE) objects = UserManager() USERNAME_FIELD = 'phone_number' @property def … -
Graphen Django Dynamic Query
Is there any way to create Dynamic queries in django graphene without mentioning object type. What I am currently doing is I created an ObjectType class and with a string type field and when I call the query i send the model name as an argument and serialize the queryset and send the json as the string field. But again, in that case I cannot take the advantages of graphQL, thats just me using graphql to get json data. Does anyone know of a proper way to implement this? -
User Follower model in Django. To show username instead of email of the people users follow
I have a custom user model and a follower system. Everything is working good, I have kind of an feed system, where it shows the actions of users which they follow. Whenever a user follows another user, its showing like: User A started following userb@gmail.com I need it to be like User A started following User B or User A started following username(user B) How to change that in my code. Please take a look at the code and thanks in advance. views @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = Account.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_from=request.user, user_to=user) create_action(request.user, 'started following', user) # TODO: change email to username else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({'status':'ok'}) except User.DoesNotExist: return JsonResponse({'status':'error'}) return JsonResponse({'status':'error'}) ajax for follow $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "posts:user_follow" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.follow').data('action'); // toggle data-action $('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link text $('a.follow').text( previous_action == 'follow' ? 'Unfollow' : 'Follow'); // update total followers var previous_followers = parseInt( $('span.count .total').text()); $('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1); } } ); … -
Adding comment -- redierecting to wrong page
this is my views.py file class PostDetailView(DetailView): model = Post form_class = CommentForm def get_success_url(self): return reverse('post_detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): post = self.get_object() request = self.request is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True comments = Comment.objects.filter(post=post) context = super().get_context_data(**kwargs) context.update({'total_likes': post.total_likes(), 'is_liked': is_liked,'comments':comments}) context['comment_form'] = CommentForm(initial={'cont': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() comment_form = self.get_comment_form() if comment_form.is_valid(): return self.comment_form_valid(comment_form) else: return self.comment_form_invalid(comment_form) def comment_form_valid(self, comment_form): comment_form.save() return super(PostDetailView, self).comment_form_valid(comment_form) this is post_detail.html ` ` ` <form method="post"> {%csrf_token%} {{comment_form|crispy}} <input type="submit" class="btn btn-outline-success" value="submit"> </form> <div class="main-comment-section"> {{comments.count}} Comment {{comments|pluralize}} {%for comment in comments%} <blockquote class="blockquote"> <p class="mb-0">{{comment.cont}}</p> <footer class="blockquote-footer">by- <cite title="Source Title">{{comment.user | capfirst}}</cite></footer> </blockquote> {%endfor%} </div> ` this is my url.py urlpatterns = [ ---- path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('like/',views.like_post,name="like_post"), --- ] this is my models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) cont = models.TextField() time = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title,str(self.user.username)) ..... when i click on submit button for posting comment i get redierected … -
How to Run Slider in Django in For Loop?
I am fetching some post from database in Slider, but when i am clicking on previous and next it's not sliding. it's going to header section after click on previous and next. Please let me know how i can activate this previous and next button in for loop in Django. Here are my code for slider.... <div class="image-post-slider"> <div class="bx-wrapper" style="max-width: 100%;"><div class="bx-viewport" style="width: 100%; overflow: hidden; position: relative; height: 293px;"> <ul class="bxslider" style="width: auto; position: relative;"> {% for bl in blog %} <li style="float: none; list-style: none; position: absolute; width: 360px; z-index: 0; display: none;"> <div class="news-post image-post2"> <div class="post-gallery"> <img src="/media/{{bl.image}}" alt="" style="width:368px; height:300px;"> <div class="hover-box"> <div class="inner-hover"> <h2><a href="single-post.html">{{bl.name}}</a></h2> <ul class="post-tags"> <li><i class="fa fa-clock-o"></i>{{bl.created_at}}</li> <li><i class="fa fa-user"></i>by <a href="#">Tech Listing</a></li> </ul> </div> </div> </div> </div> </li> {% endfor %} </ul></div><div class="bx-controls bx-has-pager bx-has-controls-direction"><div class="bx-pager bx-default-pager"><div class="bx-pager-item"><a href="" data-slide-index="0" class="bx-pager-link">1</a></div><div class="bx-pager-item"><a href="" data-slide-index="1" class="bx-pager-link active">2</a></div><div class="bx-pager-item"><a href="" data-slide-index="2" class="bx-pager-link">3</a></div><div class="bx-pager-item"><a href="" data-slide-index="3" class="bx-pager-link">4</a></div></div><div class="bx-controls-direction"><a class="bx-prev" href="">Prev</a><a class="bx-next" href="">Next</a></div></div></div> </div> -
Sending email notification in Django
I'm building a simple blog application. I have my blog up and running on development server. Now I wish to send mail to all the subscribers every time a new blog post is created by me/ admin. I know to use Django's sending_email library but I can't figure out how to automate the process, i.e, how to send the email using send_email() automatically every time I create another ' blog_post' object? Note : I'm creating new 'blog_post'objects using Django's admin interface, so basically when I 'save' the object, I want to send the email. I'm new to Django, any suggestion, guidance would be of great help -
Django Error while viewing image: TypeError at /images/anil.jpg expected str, bytes or os.PathLike object, not NoneType
I got this error while i want to view the image with the link like http://127.0.0.1:8000/images/anil.jpg but I am getting this error as I was going through a tutorial and it was working well with it.. can anyone help me here My settings.py code of URLs STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS=[ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') My urls.py codes from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.STATIC_ROOT) error I get "TypeError at /images/anil.jpg expected str, bytes or os.PathLike object, not NoneType" Please suggest me where I went wrong on this.. please -
how to solve problem highlighting qoutes sublime text 3
enter image description here sublime text 3 doesn't read quotes in html tag? how to solve the problem? Quotes highlighting pinc color -
Parsing Django form to HTML string from view(NOT from template)?
I am trying to build this : There is a button, and if the button is clicked, it sends some request to django server and server returns some form. After that, put the form into a div. So, my idea is 1. make a event handling function to handle button click event 2. put AJAX operation into the event handling function to send request and put a form into a div 3. Write view to receive request and return form that fits with request 4. the AJAX operation at Step 2 put returned form into the div But the problem is, at step 3, returning form. The form is form = EventForm({'date':date(year,month,day)}), which is ModelForm based on model Event. Because Javascript cannot understand Django form object, I need something to parse it into javascript object, like div node, or just HTML string, but I don't know :( I know there is {{ form.as_p }} for template, but I wonder if there is such function for view codes.