Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django mail_admins not sending an email
i have tried using send_mail and it work properly (its html showing value '1') but When i access localhost:8000/emailAdmins , its showing a 'none' word in html, please help me why my mail_admins doesn't work My setting EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER='myemail@gmail.com' EMAIL_HOST_PASSWORD='password' EMAIL_PORT=587 EMAIL_USE_TLS=True ADMINS = [ ('myname' , 'myemail@gmail.com'), ] My url from django.conf.urls import url from app1 import views as myapp urlpatterns = [ url(r'^emailAdmins/',myapp.sendAdminsEmail,name='emailAdmins'), ] My view from django.http import HttpResponse from django.core.mail import mail_admins def sendAdminsEmail(request): res = mail_admins('my subject', 'site is going down',) return HttpResponse('%s' %res) -
widget css Attribute not updating Authentication form django 2.1
Sorry for stupid question as i am new to programming. (Start out as a hobby and now starting a project to replace work-related task rather than using excel) trying to customize user model and extending django user models and authenication form but not updating. would prefer to use django programming to resolve the issue so as to learn more about django. (not looking at jquery override, not looking at widget-teaks) users/forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm from .models import CustomUser class CustomLoginForm(AuthenticationForm): class Meta: model: CustomUser widgets = { 'username': forms.EmailInput(attrs={'class': 'form-control'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'}), } urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from users.forms import CustomLoginForm from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('organisation/', include('organisation.urls')), path('users/', include('django.contrib.auth.urls')), path('users/login', auth_views.LoginView.as_view(template_name='registration/login.html',form_class='CustomLoginForm'), name ='login'), HTML <div class="card-body"> <form action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-group mb-3"> <label>{{ form.username.label_tag }}</label> <div class="input-group"> {{ form.username }} <span class="input-group-append"> <span class="input-group-text"> <i class="fas fa-user"></i> </span> </span> </div> </div> <div class="form-group mb-3"> <div class="clearfix"> <label class="float-left">{{ form.password.label_tag }}</label> <a href="pages-recover-password.html" class="float-right">Lost Password?</a> </div> <div class="input-group"> {{ form.password }} <span class="input-group-append"> <span class="input-group-text"> <i class="fas fa-lock"></i> </span> … -
How to retrieve external JSON file in Django Rest Framework for use with React?
On my EC2 instance, which is running Nginx and Gunicorn, I also have several json files in a directory. I ultimately want DRF to be able to return a Response object with the specified json file located in this directory. Here is what I think I should do: When a user clicks something, the onClick method will call fetch() and I will pass, say, 'api/jsonfiles' as well as the number of the file I want. urls.py will have path('api/jsonfiles/', views.JsonFileGetter). In the class JsonFileGetter within views.py, I am wondering how I can access retrieve the requested file and return a Response object containing the data? -
Connecting to AWS RDS database from a non-AWS hosting server
I am hosting my Django (2.1) app on Namecheap shared hosting and I need to connect the app to my AWS RDS Postgresql database. I can connect to the database from my local pgAdmin4 and local Django app, but my app hosted on Namecheap cannot connect. I get this error: could not connect to server: Connection refused Is the server running on host "hcdatabase.cvikoyffier8.us-east-1.rds.amazonaws.com" (3.209.46.205) and accepting TCP/IP connections on port 5432? Here are my settings for the RDS database: Port: 5432 Public Accessibility: Yes Security Group Rules: Inbound Allow All TCP (Port 0-65535) from Anywhere Subnet Group: default-vpc-0c3bc057b4c1135da I think I might have to change the Subnets to something accessible from outside of AWS but I have no idea how to do it. Any idea?? -
Web Based Software - is Django Right for Me
I have an idea for a software tool where my idea would be for it to be web-hosted where each client that I sold the product to would have their own dedicated instance of the program and each instance would have its own database. Long question made short - is Django right for this? The main purpose would be document generation and document management. It would be intended for business use. -
automatically saved value in a UpdateView Django
i'm new in Django and i'm learning about the views and the methods and how they work, especially with this problem. The thing is that I would like to know how to automatically save a value of a field in my model after updating an object in a UpdateView, for example when I update an object, in this case a report where I can assign a person to do it, I would like to save a model value that shows the "status" and save the value of "assigned" or something like that, to know if the report was already assigned or not. I know there are methods and that maybe one of them could be done by overwriting the class, but I do not know how to apply it or which one to use. For help this is a simple class of a UpdateViews that i'm using: class reporteupdate(UpdateView): model = reporte_fallo form_class = ReporteAsignar template_name = 'formulario/jefe_asignar.html' success_url = reverse_lazy('formulario:reporte_listar_jefe') and the field of the model that I would like to assign a value to is called status. i'm waiting for your help, since I'm stuck with that doubt. Thanks!!! -
Django serializing query to JSON format
I want to get the username value related to the user field within the TWEET model. Here are the two models that I am working with: class Tweet(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. user = models.ForeignKey('USER', models.DO_NOTHING, db_column='USER_ID') # Field name made lowercase. content = models.CharField(db_column='CONTENT', max_length=45) # Field name made lowercase. timestamp = models.DateTimeField(db_column='TIMESTAMP') # Field name made lowercase. like_counter = models.IntegerField(db_column='LIKE_COUNTER') # Field name made lowercase. parent_tweet = models.ForeignKey('self', models.DO_NOTHING, db_column='PARENT_TWEET', blank=True, null=True) # Field name made lowercase.True class User(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. username = models.CharField(db_column='USERNAME', max_length=45) # Field name made lowercase. email = models.CharField(db_column='EMAIL', max_length=100) # Field name made lowercase. password = models.CharField(db_column='PASSWORD', max_length=45) # Field name made lowercase. function to serialize queryset: #returns a queryset of first 5 tweets in order of most recent tweet_data = Tweet.objects.filter(user_id__in = following_ids).filter().order_by('-timestamp')[:5] tweet_data_json = serializers.serialize('json', tweet_data, fields=('id','user__username','content','timestamp','like_counter','parent_tweet')) return tweet_data_json Within serialize() I use user__username In hopes of returning the username referred to by the user value within the tweets table, however this does not appear in my json data? -
Django + Postgres: Optimize spatial query (find items within radius)
I was running the below query on local and it was running fine, but it seems it's very slow on the host. Is there any way to optimize? What I am trying to achieve is to get all Items within a radius (miles) given that a venue has a related location How am doing that: I am running this approximation method and then getting all the IDs and actually fetching the objects via the IDs. The results are not more than 20~30 Server is on Digital Ocean. DB is on Google Cloud. Ping is 38ms. .... model_class = Item if not primitive else ItemPrimitve model = "xo_item" if not primitive else "xo_itemprimitive" sql = ''' SELECT * FROM ( SELECT {model}.id, location_id, ( 3956 * 2 * ASIN( SQRT( POWER( SIN(({latitude}- xo_location.latitude) * pi()/180 / 2), 2) + COS({latitude} * pi() / 180) * COS(xo_location.latitude * pi() / 180) * POWER(SIN(({longitude} - xo_location.longitude) * pi() / 180 / 2), 2) ) ) ) AS distance FROM {model} JOIN xo_location ON xo_location.id = location_id ORDER BY distance ) items WHERE distance <= {miles} '''.format(latitude=latitude, longitude=longitude, miles=miles, model=model) return model_class.objects.filter(id__in=(i.id for i in model_class.objects.raw(sql))) -
Djanog logger.error does not save logging entry into the debug.log file
I followed the django documentation and tried to use the logger.error to save the error into the debug.log file. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } import logging logger = logging.getLogger(__name__) ...... // some code here if not data: logger.error('Search term is not valid') The sentence "Search term is not valid" does print out in the console but it is not saved to the debug.log file. I am not quite sure how Django log works. Is it supposed to behave like that or there is something wrong with my code? Also, how to save the "Search term is not valid" into the debug.log file? Thanks a lot! -
Django rest framework: error when post() for foreign key
I am trying to do simple get() post() to my database. I have existing database and I used inspectdb to generate the models.py from it. The model TestCase has foreign key relation with TestSuite model. The get() to TestCase api works well. However the post fails with below error: MultipleObjectsReturned at /dqf_api/test_case/ get() returned more than one TestSuite -- it returned 2! The browsable api calls also fail with above error models/TestCase.py class TestCase(models.Model): team_name = models.ForeignKey(TestSuite, on_delete=models.DO_NOTHING, db_column='team_name') suite_name = models.ForeignKey(TestSuite, on_delete=models.DO_NOTHING, db_column='suite_name') case_name = models.CharField(max_length=100, primary_key=True) test_type = models.ForeignKey(TestCaseType, on_delete=models.DO_NOTHING) class Meta: managed = False db_table = 'test_case' unique_together = (('team_name', 'suite_name', 'case_name'),) models/TestSuite.py class TestSuite(models.Model): team_name = models.ForeignKey(Team, on_delete=models.DO_NOTHING, db_column='team_name') suite_name = models.CharField(max_length=100, primary_key=True) description = models.CharField(max_length=200, blank=True, null=True) #Additional fields class Meta: managed = False db_table = 'test_suite' unique_together = (('team_name', 'suite_name'),) views/TestCase.py class TestCaseViewSet(viewsets.ModelViewSet): queryset = models.TestCase.objects.all() serializer_class = serializers.TestCaseSerializer views/TestSuite.py class TestSuiteViewSet(viewsets.ModelViewSet): queryset = models.TestSuite.objects.all() serializer_class = serializers.TestSuiteSerializer serializers/TestSuite.py class TestSuiteSerializer(serializers.ModelSerializer): class Meta: model = models.TestSuite fields = '__all__' serializers/TestCase.py class TestCaseSerializer(serializers.ModelSerializer): class Meta: model = models.TestCase fields = '__all__' I am new to Django and DRF.Any help is appreciated -
Django : Could not parse the remainder jinga2
In my views.py I am passing an addition context variable context['contributions']= contribution_caps_data This is a list of dictionaries. In regular python I am able to print the names as such: for i in contribution_caps_data['Data']['Members']: print(i["Name"]) However when trying to attempt the same in Django using this: {% for i in contributions['Data']['Members'] %} {{ i["Name"] }} {% endfor %} It's throwing an error: Could not parse the remainder: '['Data']['Members']' from 'contributions['Data']['Members']' -
Djando send email SSL
My site is hosted on DigitalOcean. It is configured using nginx as well as gunicorn. Python version is 3.6. No errors are shown however, nothing gets sent. Moreover I am using port 465 because the site is https Here are my configurations: Django 2.1 settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_SSL = True EMAIL_PORT = 465 EMAIL_HOST_USER = 'mygmail@gmail.com' EMAIL_HOST_PASSWORD = 'mypasswd' EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'mygmail@gmail.com' views.py from_email = settings.DEFAULT_FROM_EMAIL to_email = [settings.DEFAULT_FROM_EMAIL] contact_message = "{0}, from {1} with email {2}".format(message, first_name, email) send_mail(subject, contact_message, from_email, to_email, fail_silently=True) Thanks for your time and help -
Remove leading zeros in Django
I had a similar post earlier and deleted it because I suppose I wasnt clear enough. Nobody answered my question...so I added some more to clarify and reposted. I'm displaying data from my MySQL database. I would like to remove the leading zeros in a certain fields(the ops and obp fields), only when the value to the left of the decimal point is a 0. If the digit(s) to the left of the decimal point is not 0, then I obviously want that displayed. For instance, 0.750 becomes .750 1.000 stays as is I suspect this can be done in when calling the data using django template or in the views.py. How would I do either one? Any help on this would be greatly appreicated! Thank You. views.py from django.shortcuts import render from .models import BattingRegStd # Create your views here. def batting(request): battingregstd2018 = BattingRegStd.objects.filter(year=2018) return render(request, 'playerstats/battingReg2018.html', {'battingregstd2018':battingregstd2018}) models.py class BattingRegStd(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. obp = models.FloatField(db_column='OBP', blank=True, null=True) # Field name made lowercase. ops = models.FloatField(db_column='OPS', blank=True, null=True) # Field name made lowercase. tb = models.IntegerField(db_column='TB', blank=True, null=True) # Field name made lowercase. HTML {% extends "base.html" %} {% block contents … -
Django cannot reorder a query once a slice has been taken pagination
I'm using a class-based view inherited from django_filters.FilterView and a custom view that makes pagination easier, which in its turn inherits from django ListView. This view is supposed to render a paginated model formset with model instances to edit. Here is the view: class MyView(FilterView, CustomView): model = MyModel template_name = 'edit.html' filterset_class = MyCustomFilter # define a number of items per page paginate_by = 10 def get_queryset(self, *args, **kwargs): """ The queryset we get here is going to be paginated """ return MyModel.objects.filter(id=self.kwargs['id']) def get_context_data(self, *args, **kwargs): # Get initial context to pass to the template context = super(MyView, self).get_context_data(**kwargs) context = context or {} # Here we feed the items from the current page to the formset # i.e. paginated queryset made from the data we retrieved above formset = MyFormset(queryset=context['object_list']) context.update({'formset': formset}) return context And in the template we render the formset manually: <form method="post"> {% csrf_token %} {{ formset.management_form }} <table> <thead> <tr> <th>Name</th> <th>Id</th> </tr> </thead> <tbody> {% for form in formset %} <tr> <td>{{ form.name }}</td> <td>{{ form.id }}</td> </tr> {% endfor %} </tbody> </table> </form> But any time on render it fails with the error from the title on formset.management_form line. Is it … -
ModelForm for choicefield with PK instead of usernames
I have a form generate by a PostView class HotelCreateView(LoginRequiredMixin, CreateView): model = Hotel fields = ['hotel','code','collaborateurs', 'planning' 'payday'] def form_valid(self, form): form.instance.manager_hotel = self.request.user return super().form_valid(form) The model collaborateurs is a choicefield which render the usernames. I want this field to render PK instead so I tried to create my own form but could not figure out. forms.py from django import forms class HotelForm(forms.Form): collaborateurs = forms.ColleagueChoiceField(label_from_instance('pk')) Thanks -
Moving from C# to Python: Best way do do Threads in Python?
I am trying to port and old C# WinForms application to a Python Django application and wondering what's the best way to do threading in Python. Each thread in the original application (there could be easily up to 20) does a lot of web scraping / website monitoring, i.e. sends a lot of HTTP requests and deals with the answer. How would you accomplish this ? "Real" Python threads or better something like Celery? -
Why the pages can't get show in my Django CRUD application?
I try to learn Django CRUD from this tutorial: https://www.javatpoint.com/django-crud-example My Django version is 2.1.7 and my IDE is VisualStudio. When I run the project all the pages have an error. the error cames bellow. TemplateDoesNotExist at /index show.html Request Method: GET Request URL: http://localhost:52322/index Django Version: 2.1.7 Exception Type: TemplateDoesNotExist Exception Value: show.html Exception Location: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\Scripts\python.exe Python Version: 3.6.6 Python Path: ['E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5', '', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\Scripts\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\lib\\site-packages'] Server time: Tue, 5 Mar 2019 22:43:24 +0000 I add my Urls bellow: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from employee import views urlpatterns = [ path('index', views.show), path('admin/', admin.site.urls), path('emp', views.emp), path('show',views.show), path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] I think the error says the template does not exist but the templates exist. Please inform me what is wrong in my application. -
how to pass django context to create react app
I set up create-react-app with django following this example. The webpage get passed in the views like this: def get(self, request): try: with open(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f: return HttpResponse(f.read()) I'm trying to pass conext (conext = {'foo':'bar'}) to it now. I tried via get_context_data: class MyView(DetailView): """ Serves the compiled frontend entry point (only works if you have run `yarn run build`). """ def get(self, request): try: with open(os.path.join(settings.MY_VIEW_DIR, 'build', 'index.html')) as f: return HttpResponse(f.read()) except FileNotFoundError: return HttpResponse( """ This URL is only used when you have built the production version of the app. Visit http://localhost:3000/ instead, or run `yarn run build` to test the production version. """, status=501, ) def get_context_data(self, *args, **kwargs): context = super(MyView. self).get_context_data(*args, **kwargs) context['message'] = 'Hello World!' return context I also tried turning the web page into a template and return return render(request, 'path/to/my/index.html', {'foo':'bar'}) But that just returns the page without my react code. Is there a better way to implement create-react-app with django or a way to convert the react code into a template? -
restricting some pages to only specific users
I am creating a blog app in django but I don't want any random person to be able to make a post. I want to make sure only the people who i give permission to can type post. I saw the django documentation for it and found the has_add_permission(), has_change_permission() and has_delete_permission() methods provided by the ModelAdmin class, but i was unable to figure out how will they interact with the Post model and what exactly the syntax would look like. if anyone could provide a reference i'd be grateful. -
User doesn't exists and no redirect to created tenant in django project
I have an application in django 1.11 where I use django-tenant-schemas (https://github.com/bernardopires/django-tenant-schemas) to create an account for the user. After creating a client and schema and domain_url, the user is not redirected to the address given in domain_url. For example: I have domain_url = test.localhost in the form. After creating an account, I am still on localhost instead of test.localhost. When I go to test.localhost I get a login panel. I log in with the data I provided when creating, but I get a message to enter the correct data. I check the database using shell - the user exists. The user is connected to the Company using ForeignKey. accounts/view.py def signup(request): if request.method == 'POST': company_form = CompanyForm(request.POST, prefix='company') user_form = SignUpForm(request.POST, prefix='user') if company_form.is_valid() and user_form.is_valid(): company_form.instance.name = company_form.cleaned_data['name'] company_form.instance.domain_url = company_form.cleaned_data['name'] + '.localhost' company_form.instance.schema_name = company_form.cleaned_data['name'] company = company_form.save() user_form.instance.company = company user = user_form.save() auth_login(request, user) return HttpResponseRedirect(reverse('qa:qa_list')) else: company_form = CompanyForm(prefix='company') user_form = SignUpForm(prefix='user') args = {} args.update(csrf(request)) args['company_form'] = company_form args['user_form'] = user_form return render(request, 'accounts/signup.html', args) Forms to create company and user: class CompanyForm(forms.ModelForm): name = forms.CharField(label='Company', widget=forms.TextInput(attrs={'autofocus': 'autofocus'})) class Meta: model = Company fields = ('name',) class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, required=True, … -
Django: adding a form from one app into another's app template (detail view)
I want to add a form for the user to add a rating and a review comment, which updates a model from another app (rating app & items app). I've been struggling with this for a while. Right now I have: Ratings MODELS.py class Avaliacao(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) created_at = models.DateTimeField(auto_now=True) usuario = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) safra = models.ForeignKey(Safra,blank=False,on_delete=models.SET_NULL,null=True) nota = models.IntegerField(choices=RATING_CHOICES) comment = models.TextField() forms.py class NotaFormulario(ModelForm): class Meta: model = Avaliacao fields = ['nota','comment'] urls.py urlpatterns = [ url(r'^safra/(?P<safra_id>[0-9]+)/add_review/$',views.add_review, name='add_review') ] views.py def add_review(request, safra_id): safra = get_object_or_404(Safra, pk=safra_id) form = NotaFormulario(request.POST) if form.is_valid(): nota = form.cleaned_data['nota'] comment = form.cleaned_data['comment'] usuario = request.user avaliacao = Avaliacao() avaliacao.safra = safra avaliacao.usuario = usuario avaliacao.nota = nota avaliacao.comment = comment avaliacao.created_at = datetime.datetime.now() avaliacao.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('vinhos:safra_detalhes', args=(safra.id,))) return render(request, 'vinhos/safra_detail.html', {'safra': safra, 'formulario': form}) template.html (which is my detail template from another app) <form action="{% url 'notas:add_review' safra.id %}" method="post" > {% csrf_token %} {{ formulario }} <input type="submit" value="Enviar" class="btn btn-primary btn-large"> </form> … -
django-cron job inside crontab is not working?
I'm usign django-cron library, when I issue the following command : python manage.py runcrons It runs OK, but when setting it inside corntab is not working. I have used the following cornjob inside corntab: SHELL=/bin/bash */1 * * * * root source /var/path_to_venv/bin/activate && cd /var/path_to_project && /usr/bin/python3.6 /var/path_to_project/manage.py runcrons --settings Project.settings.production > /var/log/cronjob.log 2>&1 Any Ideas what is the reasons for that? -
Render multiple content from different users in the same page
I have a page where users can post messages. I have a filter so only people form within the group can see the page but so far only I can see my messages Models.py class Hotel(models.Model): manager_hotel = models.ForeignKey(User, on_delete=models.DO_NOTHING,verbose_name="Nom de l'utilisateur", related_name='manager_hotel') collaborateurs = models.ManyToManyField(User, verbose_name="Liste des collaborateurs autorisés") messages = models.ManyToManyField(TeamMessage, verbose_name="Messages de l'équipe") views.py class HotelListView(LoginRequiredMixin,ListView): model = Hotel def get_queryset(self): return self.model.objects.filter(collaborateurs=self.request.user) list.html {% for Hotel in object_list %} {% for TeamMessage in Hotel.messages.all %} {TeamMessage.text }} {% endfor %} {% endfor %} -
I want to learn django where should i start? [on hold]
I have some knowledge about python and i want to learn django further. where should i start? I take and online course for django but most of the things go over my head .can any one please help me with that? -
django-oauth-toolkit logout issue with not prompting the user for username/password every time
I cannot find any information about this issue anywhere online, so I'm going to put it here! I'm using a frontend application which redirects to a custom auth_views.LoginView on the backend (django-oauth-toolkit) with the client_id, etc. I have all of this working. (I'm using implicit grant, btw). The problem is when the user logs out, I use /o/revoke_token, which successfully removes the token from the db. However, when the user will turn around and log back in, it never prompts them for their username/password again. The auth_views.LoginView will give a 302 and redirect back to the frontend with a valid api_key. How can I prevent this? I want to prompt the user EVERY TIME they hit that page for their username/password. This way, they can log out and log back in with a different user, if necessary.