Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
social auth app django Google Auth After Register Say Your Account Is ALready Exist
I Put Social Google Auth In My Website Complete Register And I Can Login in My Website First Time With One Google Account But At Second Time Say To Me Your Account Exist And Dont Just Like Normal Login To Website Becuase I Registered Before And Give Me Error That Your Account Already Exist I Want To Now How To Fix It . -
Django PasswordResetConfirmView not setting new password
I am trying to use a Custom PasswordResetConfirmView template. Since the default form has no styling and I am trying to put a custom class in it. Here is my forms.py: from django.contrib.auth.forms import PasswordResetForm class UserPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super(UserPasswordChangeForm, self).__init__(*args, **kwargs) new_password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Password', })) new_password2 = forms.CharField(label='Conform Password', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Confirm Password', })) Here is urls.py: from django.contrib.auth import views as auth_views path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html', form_class=UserPasswordChangeForm, success_url=reverse_lazy('password_reset_complete')), name='password_reset_confirm'), When I put new_password1 and new_password2, it does not save the new password, or even show erorrs. -
How can i compare two DateTimeFields with current time
Event has two DateTimeField's and i need to compare them to the actual date time in a same method. from django.utils import timezone event_starts = models.DateTimeField(_("Event starts")) registration_closes_at = models.DateTimeField( _("Registration ends:"), null=True, blank=True ) This is what i have tried, but it doesn't work. So what i need is: If event has been started or registration was closed user can not attend this event. def is_registration_open(self): now = timezone.now() passed_registration = now > self.registration_closes_at passed_start = now > self.event_starts if not passed_registration or not passed_start: return And tried this: def is_registration_open(self): if ( not timezone.now() > self.registration_closes_at or not timezone.now() > self.event_starts ): return Here is a fail: '>' not supported between instances of 'datetime.datetime' and 'NoneType' When i compare only event_starts everything is working fine. Thanks for help! -
Django two or more droplets sharing same sqlite database?
For one of my use-case I had to use a local sqlite database for one of my model. But as I am using load-balancing for my project, I cannot use two databases as all droplets would have different database. So, I was trying to find a way in which I can use a single local database in one of my droplet and then let other droplets read/write from this database. Is there any way to achieve this? -
Changing the size of bootstrap cards in a Django project?
I'm working on a simple Django project with bootstrap. I have a set of cards being displayed on a page, and the cards are showing just fine (Don't mind the place holder images). I've been reading the bootstrap docs about cards, but since I have less knowledge of CSS than I'd like, I can't figure out how to simply change the size of the cards so they are larger and stacked in rows instead of one column. This is my HTML template for this page. It just uses a for-loop to go through my projects and make a card for each. You can see I have the title and text worked out, and the URL to 'See Details'. {% extends "base.html" %} {% load static %} {% block page_content %} <h1>Projects</h1> <div class="row"> {% for project in projects %} <div class="col-md-4"> <div class="card mb-2"> <img class="card-img-top" src="{% static project.image %}"> <div class="card-body"> <h5 class="card-title">{{ project.title }}</h5> <p class="card-text">{{ project.description }}</p> <a href="{% url 'project_detail' project.pk %}" class="btn btn-primary"> See Details </a> </div> </div> </div> {% endfor %} </div> {% endblock %} The Base.html is just linking to the bootstrap and all the html for the top of the page. Hopefully … -
How to Update Multiple Images of product in django
how to edit images of product to form edit product models.py: class Product(models.Model): title = models.CharField(max_length=200, verbose_name='title') text = models.CharField(max_length=200, verbose_name='text') thumbnail = models.ImageField(upload_to=get_file_path, verbose_name='thumbnail') def __str__(self): return self.title class Product(models.Model): id_product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE, related_name='products',verbose_name='product') photo = models.ImageField(upload_to=get_file_path, verbose_name='photo') thanks -
fix problem any user can change password for admin user site using UserCreationForm - django
I am new in Django and even after trying thoroughly to find an answer for this question, I couldn't find any. the problem is any user can change password for admin user site using UserCreationForm , i mean any user can use reset password form he can change my profile in admin page i don't want allow users change admin profile how to fix this problem ? -
Model UserProfile object has no attribute 'save'
So, I am trying to create an API user registration endpoint on my Django + DRF project. Whenever a user is registered it should create also a user profile. But, I am getting this error while printing sys.exc_info(): AttributeError("'UserProfile' object has no attribute 'save'") I am reading how to create objects in Django documentation says: from blog.models import Blog b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') b.save() So, I have tried that, I guess; this is where everything stops working: try: profile = UserProfile(user=user) if 'picture' in request.data: profile.picture = request.data['picture'] profile.save() except: print('USER PROFILE CREATION', sys.exc_info()) try: user.delete() except: print('USER DELETE ON PROFILE CREATION ERROR', sys.exc_info()) return Response(result, status=500) And this is my model definition: class UserProfile(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) picture = models.ImageField( "Profile picture", upload_to='profiles/', blank=True ) created_at = models.DateTimeField("Created at", auto_now=False, auto_now_add=True) updated_at = models.DateTimeField("Updated at", auto_now=True) def __str__(self): return f'{self.user} user profile' class Meta: verbose_name = 'User Profile' verbose_name_plural = 'User Profiles' What am I doing wrong? -
Elastic beanstalk won't process wsgi.py as a python module stating "No module named vine.five"
I'm trying to re-host a Django app on Elastic Beanstalk. It had been working find prior to mothballing it in August last year. After spinning it up I get a 500 error. The logs show this: Target WSGI script '/opt/python/current/app/app_name/wsgi.py' cannot be loaded as Python module. Exception occurred processing WSGI script '/opt/python/current/app/app_name/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/app_name/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/opt/python/current/app/app_name/__init__.py", line 5, in <module> from .celery_settings import app as celery_app File "/opt/python/current/app/app_name/celery_settings.py", … -
Creating Evaluated Field in Django By Applying Aggregation 2 Fields
I am in phase of learning Django framework and I need some help to understand how to generate an evaluated field by summing up two inputs by user. I've used the code below where ops1 and ops2 will be provided by user and I need to show their sum in field total_ops at runtime. I've used the code below but that doesn't seems to work. class ManHour(models.Model): date = models.DateTimeField(auto_now=True) class Operations(models.Model): ops1 = models.DecimalField(max_digits= 5, decimal_places= 3) ops2 = models.DecimalField(max_digits= 5, decimal_places= 3) total_ops = Operations.ops1 + Operations.ops2 Error from code above TypeError: unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute' -
Unit rabitmq-server.service could not be found
I run the following commands on Ubuntu 20.04 sudo apt-get install rabbitmq-server sudo systemctl enable rabbitmq-server sudo systemctl start rabbitmq-server systemctl status rabitmq-server enter image description here and get this output Unit rabitmq-server.service could not be found. I got similar problem using redis, both locally and on heroku. Please help me. -
Python how to download multiple files, zip them and return zip file
I need to download multiple images, write them into a zip archive and then have the client download said zip file. Currently this is the code that I have, the problem is that the zip files that are downloaded are always 67 bytes in length and are corrupted. def get(self, request): import requests from zipfile import ZipFile from io import BytesIO imgs = [ 'https://i.ytimg.com/vi/MPV2METPeJU/maxresdefault.jpg', 'https://www.cdc.gov/healthypets/images/pets/cute-dog-headshot.jpg', ] response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = f'attachment; filename=Photos.zip;' mem_file = BytesIO() with ZipFile(mem_file, "w") as zip_file: for img in imgs: resp = requests.get(img) filename = img.split('/')[-1] zip_file.writestr(filename, resp.content) mem_file.seek(0) response.write(zip_file) return response I suppose I'm either using either the ZipFile or BytesIO incorrectly, any help is greatly appreciated. -
How to update every record in a model in django
I am trying to update every record in the model Lead whenever I update or create the model Holiday. Here is the signal in my models.py: # update all leads when holiday is newly created or edited def post_holiday_created_signal(sender, instance, created, **kwargs): Lead.objects.update() post_save.connect(post_holiday_created_signal, sender=Holiday) I need each of the records in the Lead model to update after Holiday has been edited or created. However, I am not sure if the above code works properly or not. I want the equivalent of going into each of the lead's update view and clicking the update button. I also want to mention that the lead-update view also has a def form_valid method, and I need that to work as well. Could you look at the code, and tell me if it works. If not, could you suggest some methods to do this? Thanks a lot. -
column id does not exist Heroku
I added id column, migrate --fake-initial, migrate --fake contacts zero, dropping dp and recreate. Im really lost. if someone know please help me out. Thanks in advance https://buildblock-site.herokuapp.com class CompanyInformation(models.Model): id = models.AutoField(primary_key=True, unique=True) -
object after calling DestroyAPIView still exist
I have a web scraper with a no. of urls. I can manually subscribe or unsubscribe to the urls. Although, when I try to unsubscribe a list of urls, the log info says that they are deleted but I can still see them in the list of subscribed urls. Below is my code class SubscribeView(ListCreateAPIView): queryset = WebS.objects.all() serializer_class = WebSSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) instance = serializer.save() for i in instance: # do something return Response(serializer.data, status=status.HTTP_201_CREATED) class UnsubscribeView(DestroyAPIView): queryset = WebS.objects.all() serializer_class = WebSSerializer lookup_field = 'url' def post(self, request, *args, **kwargs): urls = request.data WebS.objects.filter(url__in=urls).delete() return Response(status=status.HTTP_204_NO_CONTENT) Note: I have used post in DestroyAPIView because by overriding delete or destroy I could not manually provide data in my API. The textbox was disabled, strangely. -
How do I send my updated data and save it using Bootstrap Modal in django?
I am trying to use Boostrap Modal to pop up an edit form that should send the thought and its id to my views function using Ajax, edit, and save it. However, when I press the Save Changes button on my modal, nothing happens. Being very new to this, I can not figure out exactly where to go on the internet so it would be great for me if anyone here could direct me on what to read and what I'm doing wrong. my html - <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Edit</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method = "POST" enctype= multipart/form-data id = "editt"> {% csrf_token %} <textarea id = 'thought' style="resize:none" type = "text" placeholder = "{{ obj.thought }}." rows = "5" cols = "40" name = "thought" required></textarea><br> </div><br> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <a type = "button" data-catid = "{{ obj.id }}"><button type="button" class="btn btn-primary submit" id = "upload-form-btn">Save changes</button></a> </form> </div> </div> <script type="text/javascript"> $('.submit').click(function(){ var form = $('#editt'); var btn = $('#upload-form-btn'); var id = $(this).attr("data-catid"); var el = document.getElementsByName("csrf_token"); csrf_value = … -
in ubuntu using the command "adduser (newusername)" cant login as that newly created user
I'm using Linode to deploy my django application. I'm using windows 10 using bash. After creating a new server I was able to log in as the root user just fine. when I try to create a new user using the command "adduser" NOT "useradd"(I saw a lot of issues involving useradd) Im using "adduser (newusername)" and it creates the user. then when I try to log in as that newly created user the bash tells me "permissions denied, please try again". I made sure I'm entering the correct password, even tried creating a couple different new users and changing the password the users I created but I get the same error. Does anyone know what I'm doing wrong??? -
TreeNodeChoiceField not iterable in a form - Django
I was wondering if someone was familiar with TreeNodeChoiceField from mptt in Django. I am trying to use this feature in a form to post an article on a blog. But when I try to create a new post it says that the object associated is not iterable. This doesn't happen with a get method or when I simply use a forms.ModelMultipleChoiceField. I was thus wondering if someone knew how I could use TreeNodeChoiceField without this issue. Thank you for any input!! Here is the forms.py class BlogForm(forms.ModelForm): sdg = forms.ModelMultipleChoiceField( queryset=SDG.objects.all(), widget=forms.CheckboxSelectMultiple ) value_chain = TreeNodeChoiceField(queryset=Value_chain.objects.all()) industry = forms.ModelMultipleChoiceField( queryset=Industry.objects.all() ) class Meta: model = Blog fields = ["title", "sdg", "value_chain", "industry", "contenu"] and here is my views.py def blog_create(request): if request.method == "POST": blog_form = BlogForm(request.POST) docu_form = DocumentFormBlog(request.POST, request.FILES) if blog_form.is_valid() and docu_form.is_valid(): blog_form.instance.user = request.user blog = blog_form.save() docu_form.instance.blog_related = blog docu_form.save() messages.success(request, 'Your blog was successfully created!') return redirect('knowledge:search_blog') else: messages.error(request, 'Please correct the error below.') else: blog_form = BlogForm(request.POST) docu_form = DocumentFormBlog(request.POST, request.FILES) return render(request, "dist/inside/knowledge/blog/create_blog.html", context={"blog_form": blog_form, "docu_form": docu_form}) -
Custom QuerySet returns empty
I want to create a custom QuerySet where it contains filters with model instances being filtered by date durations. Upon attempting to test DateRangeQuerySet.week_long(), no models are being returned. Upon debugging, a TypeError is being raised in Django's BaseManager class: TypeError: isinstance() arg 2 must be a type or tuple of types. https://github.com/django/django/blob/e4430f22c8e3d29ce5d9d0263fba57121938d06d/django/db/models/manager.py#L81 What is causing this TypeError to be raised and why is this causing an empty QuerySet to be returned? class TestQuestionDateRangeQuerySet(TestCase): '''Verify that each queryset method filters all questions in the database by a prescribed date time delta''' @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="tag1") user = User.objects.create_user("User") user_account = UserAccount.objects.create(user=user) for q in mock_questions_submitted: q.update({'user_account': user_account}) question = Question.objects.create(**q) question.tags.add(tag1) q1, q2, q3, q4 = Question.objects.all() def test_questions_posted_week_ago(self): with patch('datetime.date') as mock_today: mock_today.today = Mock(return_value=datetime.date(2021, 3, 13)) week_old_questions = Question.dateranges.weeklong() mock_today.assert_called_once() self.assertEqual(week_old_questions.count(), 2) self.assertQuerysetEqual( week_old_questions, map(repr, [q1, q2]) ) class DateRangeQuerySet(models.QuerySet): def week_long(self): today = datetime.date.today() week_ago = today - datetime.timedelta(days=7) return self.filter(dated__range=(week_ago, today)) def month_long(self) pass class Question(models.Model): title = models.CharField(unique=True, max_length=50) body = models.TextField() dated = models.DateField(default=datetime.date.today) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() class Meta: ordering = ['dated'] default_manager_name … -
how to ignore FileField data if its empty in django
i am new in django and tryng to learn more but cannt find solution i want to make django ignore form if form is empty and only change other txt input it is editor to edit info and when it opens it fills info automaticly and if you want u can add word or leave as it is problem is to i have to select image every time how can i make django ignore that input ? here is code forms.py picture = forms.ImageField(widget=forms.TextInput(attrs={'class':'file-input'}), required=False ), profile_info = forms.CharField(widget=forms.TextInput(attrs={'class':'textarea'}), max_length=260, required=False) class Meta: model = Profile fields = ('picture','profile_info') views.py def EditProfile(request): user = request.user.id profile = Profile.objects.get(user__id=user) BASE_WIDTH = 400 # self.objects.exclude(file__isnull=True) i am tryng to put this code but dont works? if request.method == 'POST': form = EditProfileForm(request.POST, request.FILES) if form.is_valid(): profile.picture = form.cleaned_data.get('picture') profile.profile_info = form.cleaned_data.get('profile_info') profile.save() return redirect('index') else: form = EditProfileForm() context = { 'form':form, } return render(request, 'edit_profile.html', context) please someone guide me how to fix this -
Django widget for Array of Points
I have a model with field myfield = ArrayField(geo_models.PointField(null=False, blank=False), null=False) And I can't find a way to represent it in Django Admin. I tried to use django_better_admin: from .widget import PointWidget from django_better_admin_arrayfield.admin.mixins import DynamicArrayMixin @admin.register(myModel) class MyModelAdmin(admin.ModelAdmin, DynamicArrayMixin): formfield_overrides = { DynamicArrayField: {'widget': PointWidget}, } And PoinWidget: class PointWidget(forms.MultiWidget): """ A Widget that splits Point input into latitude/longitude text inputs. """ def __init__(self, attrs=None, date_format=None, time_format=None): widgets = (forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs)) super(PointWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return tuple(value.coords) return (None, None) def value_from_datadict(self, data, files, name): mylat = data[name + '_0'] mylong = data[name + '_1'] try: point = Point(float(mylat), float(mylong)) except ValueError: return '' return point But still there's only one TextField in the form and no way to fill it -
Django makemigrations error on many to many relationship
What i want: Store information about running of group of people. What i did: from django.db import models from django.contrib.auth.models import User from datetime import timedelta class Route(models.Model): name = models.CharField(max_length=50) class Run(models.Model): date = models.DateField() type = models.ForeignKey(Route, on_delete=models.PROTECT) runners = models.ManyToManyField(User, through='RunnerResult', through_fields=["user", "run"]) class RunnerResult(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) run = models.ForeignKey('Run', on_delete=models.PROTECT) result = models.DurationField(default=timedelta()) Problem: When i do makemigrations i have the following error: SystemCheckError: System check identified some issues: ERRORS: run.Run.runners: (fields.E339) 'RunnerResult.run' is not a foreign key to 'User'. HINT: Did you mean one of the following foreign keys to 'User': user? run.Run.runners: (fields.E339) 'RunnerResult.user' is not a foreign key to 'Run'. HINT: Did you mean one of the following foreign keys to 'Run': run? Tried to swap through_fields and models between each other and some other actions. I'm starting to think of my misunderstanding of M2M relationship. -
Logging requests and responses sent from django heroku app
I'm wanting to capture all http requests made from my django app hosted on heroku. I'm wanting all of the information regarding the request that was made and the response of that request (including the body for both GETs and POSTs). I currently have sentry attached to my app and it looks like it captures all requests made when there is an error in the app (although it doesn't include the body). I'm wondering if there is an easy way to use sentry or some other heroku add on the capture all outgoing http traffic from my app. Or do I have to tap into the python logging module to achieve this? -
Spacing between bootstrap 5 cards
i already made a question like this, but people didn't give good enough answers, so I'm just going to paste the link of that post here. Please answer on that post. How to space bootstrap 5 cards? Thanks! -
Database not displayed on admin, gives template error "model" has no attribute user
So i created a new modelform that is functioning perfectly, interesting enough i receive an template error when i try to see the base model on admin. And it shows this weird line as the causer. <a href="{% url 'admin:password_change' %}">{% translate 'Change password' %}</a> / This problem is probably caused by auth_views, specially one involving password changes, so here it is my project urlpatterns code that migth help. urlpatterns = [ path('admin/', admin.site.urls), #Essas views sao relacionadas o usuario path('Cadastro/', usuarios_views.Cadastro, name= 'Cadastro'), path('Empresa/', usuarios_views.Empresa, name= 'Empresa'), path('Login/', auth_views.LoginView.as_view(template_name='usuarios/login.html'), name= 'Login'), path('Logout/', auth_views.LogoutView.as_view(template_name='usuarios/logout.html'), name= 'Logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='usuarios/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='usuarios/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='usuarios/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='usuarios/password_reset_complete.html' ), name='password_reset_complete'), path('', include('APP_IVG.urls')), path('Dado/', include('dado.urls')), ] Any extra info just ask and i shall give it.