Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to link two projects django
I need to link two projects Django. both of them project are run in the same server. What tools or file I need for this goal? when I click on some button in my current project's page I should get a page from the other project.. Can you suggest a way to do? -
2 different django User models
i have 2 different django User models, one for the clients and one for the admins, The reason for this was that I didn't want the two types of users to be mixed in one model. But I have a problem logging in for the clients users, I can't match their password with each other in View, because the password is saved as hash, but the password that they enter is the same password that they choose to register. def login_view(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] try: user = CustomUsers.objects.get(email=email, password=password) except CustomUsers.DoesNotExist: user = None if user is not None: login(request, user) return redirect('/') else: return redirect('login') else: form = UserLoginForm return render(request, 'CustomUsers/login.html', {'category': Category.objects.all(), 'form': form}) any solution...? also another question, Will I have trouble later to hiding the registry phrase in the Template when they are logged in? Or also can use {% if.is_authenticated %} again. -
Can anyone tell me free courses for Django from beginner to advanced?
Please tell me any Django free courses that are available from beginner to advanced..... -
postfix slow in outgoing connection
I tried to send an email from usermin and there is no problem it is instance but when I try to send it from django app the delay vary from 3 sec to 1 min I tried gmail it was steady so I notice the problem with the outgoing connection where is both port were 587 and I tried 25 for postfix nochange. -
Django Rest Framework - URL Queries Not Working?
I am writting an application in Django that uses the Django Rest framework. A GET request to the API URL works, but when I add a query to it, such as '?id=1845' it does not actually perform a query, it still returns the full list of results. In the below code, I am trying to query the 'Indicator List' views.py ''' from django.shortcuts import render from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import IndicatorSerializer from data_platform.models import Indicator @api_view(['GET']) def apiOverview(request): api_urls = { 'Indicator List':'/indicator-list/', 'Indicator Detail':'/indicator-detail/<str:pk>/', } return Response(api_urls) ''' urls.py ''' from django.urls import include, path from . import views urlpatterns = [ path('', views.apiOverview, name="api-overview"), path('indicator-list/', views.indicatorList, name="indicator-list"), path('indicator-detail/<str:pk>/', views.indicatorDetail, name="indicator-detail"), ] ''' serializers.py ''' from rest_framework import serializers from data_platform.models import Indicator class IndicatorSerializer(serializers.ModelSerializer): class Meta: model = Indicator fields = '__all__' ''' -
Ordering in Django Rest Framework?
if i used OrderingFilter class from DRF filters, is it will use order_by function or what it use? Example from django_filters import DjangoFilterBackend from rest_framework import viewsets, filters class InvoiceViewSet(viewsets.ModelViewSet): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer filter_backends = (DjangoFilterBackend, filters.OrderingFilter) ordering_fields = ('items', 'table', 'published_date') -
How to insert and fetch data fin database in django
Hey I am working on a semester project and making a web app but i am totally new to django and i do not know how to insert data or retrieve. I have been struggling from two days and read a lot of articles and watched a lot of videos on youtube and tried all this but it is not working. Kindly help me out. ** JUST WANT TO DO WITHOUT USING HTML FORMS. ** Here is my html code: <div class="input-group mb-3"> {% csrf_token %} <input type="text" name="Name" method="post" id="padding-box" class="form-control" placeholder="Name" required> </div> <div class="input-group mb-3"> {% csrf_token %} <input type="text" name="username" method="post" id="padding-box" class="form-control" placeholder="Username" required> </div> <div class="input-group mb-3"> {% csrf_token %} <input type="password" name="password" method="post" id="padding-box" class="form-control" placeholder="Password" required> </div> <div> {% csrf_token %} <button type="submit" onclick="location.href='{% url 'register/' %}'" name="submit" class="button">Register</button> <br> <br> <br> </div> and this is my views.py: from django.http import HttpResponse from django.template import loader from django.shortcuts import render from .models import User def login(request): all_users = User.objects.all() template = loader.get_template('ActivitySchecdulingApp/login.html') context = { 'all_users': all_users, } return HttpResponse(template.render(context, request)) def register(request): all_users = User.objects.all() template = loader.get_template('ActivitySchecdulingApp/register.html') context = { 'all_users': all_users, } return HttpResponse(template.render(context, request)) def getin(request): if request.method … -
How to use model objects as choices for django-filter MultipleChoiceFilter
I'm using Django-filter, and I would like one of the fields (supervisor) to be a ChoiceFilter where the choices are objects from the model. What's the most efficient way to do that? I tried following this post, but kept getting errors no matter what I changed (currently cannot unpack non-iterable int object). # models.py class people(models.Model): namelast = models.CharField(max_length=100, verbose_name='Last Name') namefirst = models.CharField(max_length=100, verbose_name='First Name') supervisor = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Supervisor') def __str__(self): return "%s %s" % (self.namefirst, self.namelast) # filters.py class office_filter(django_filters.FilterSet): supervisor = django_filters.ChoiceFilter(choices=[], lookup_expr='icontains', label='Supervisor') # other fields class Meta: model = people fields = ['namelast', 'namefirst', 'supervisor'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: self.filters['supervisor'].extra['choices'] = [x for x in people.objects.all().values_list('supervisor', flat=True).distinct()] except (KeyError, AttributeError): pass The goal is to have the supervisor field be a nice menu of all of the people that have been added assigned as a supervisor in the people model. -
PIP returns an error while installing scikit-image
I'm using Windows 10 v2003 While trying to install scikit-image==0.14.5 using CMD.exe, I am getting the following error the error is present here link: https://gist.github.com/Debagnik/b88f1a6aafe6f948ce5f69b50d1e6966 please help me solve it. Also, I am fairly new to image processing. -
When to create a virtual environment for django project?
I created my first virtual environment for a django app that I created following a tutorial guide. Now I'm not sure, can I use this very same environment (same name), or do I need to create a new virtual environment when I create a new project? If I were to use the same named virtual environment for this new project, what would the implications be? -
Map Display Web GIS django heroku
I am newbie in web development and today I get task to develop web GIS application using Django framework and then host to heroku. There's a scenario to filter out my data from database before combining with my spatial data (GeoJSON) which I've saved as static file in Django. After that, those combination data add to Leaflet.js basemap as an overlay map. The problem raise when I try to open my web but the overlay map doesn't appear on my screen. Thus, I try to refresh my web page several time and unfortunately the overlay map appear and disappear alternately without a constant pattern. I've stuck for several days because there's no bit of error message appear on the screen eventhrough my debug method still be True in Django settings. Could anyone tell me what's the error possibility and what should I do now for debugging my problem, please? Very pleasure to have your help :) Thank you -
Sending email in django
I am trying to send email in django. i followed django documentation(https://docs.djangoproject.com/en/3.0/topics/email/#quick-example) But I am getting an error. The error: smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError q1sm10062648pfk.132 - gsmtp', '*******nl@gmail.com') I have configured less secure app from google account. -
Django pagination page_obj.number is not changing
I have following view and the content is rendered correctly. The pagination is also correct. The only issue is that the page_obj.number in the template is always 1. Even clicking on page 3 the content of page 3 is shown but the page_obj.number is still 1. Maybe I'm doing something wrong in my view. Here the view: class SpecificationListView(AjaxRequiredMixin, ListView): model = Category context_object_name = 'categories' template_name = 'catalog/specification/listSpecificationFiltered.html' paginate_by = 2 def get_queryset(self): search_value = self.request.POST.get('searchValue', None) sel_category = self.request.POST.get('selCategory', 'ALL') chk_active = self.request.POST.get('chkActive', 0) category_filters = Q() if sel_category != 'ALL': category_filters = category_filters & Q(pk=sel_category) specification_filters = Q() search_value = None if (search_value == '' or len(search_value) < 3) else search_value if search_value is not None: specification_filters = specification_filters & Q(name__icontains=search_value) if chk_active == '1': specification_filters = specification_filters & Q(is_active=True) # categories are retrieved to build the tree in template categories_list = Category.objects.distinct().filter(category_filters) category_ids = categories_list.values_list('id', flat=True) # category ids on page specification_filters = specification_filters & Q(category_id__in=category_ids) categories_list = categories_list.prefetch_related( Prefetch( 'specifications', queryset=Specification.objects.filter(specification_filters) ) ) return categories_list def post(self, request, *args, **kwargs): return self.get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(SpecificationListView, self).get_context_data(**kwargs) page = self.request.POST.get('page') paginator = Paginator(self.get_queryset(), self.paginate_by) categories = paginator.get_page(int(page)) context.update({ 'categories': categories, 'page_title': … -
Django: How to read POST passed field/values into a new Object, dynamically
happy issolation. So: I have a project with some tables: "Empresa" (enterprise), is one of them, for the companies. Then we have "Employees" and "Projects" but lets focus on Empresa. class Empresa(models.Model): Sujeto = models.CharField('Nombre', max_length=10, primary_key = True) #"Sujeto" (Subject) is the enterprise name, 1ary key. Razon = models.CharField(max_length=20, unique = True) Direccion = models.CharField(max_length=40) Telefono = models.CharField(max_length=10) def __str__(self): return self.Sujeto + self.Razon_social + self.Telefono This is an 'store' view called by a SUBMIT in a form, that passes add the data input in the form as a new register in model Empresa and saves it. With these explicit fields, it works fine. def store (request): Sujeto = request.POST['Sujeto'] Name = request.POST['Name'] Razon = request.POST['Razon'] # Each exisiting field takes the value pased in post Tel = request.POST['Tel'] Address = request.POST['Address'] try: new_ent = Empresa.objects.get(RUT=rut) #...we try getting the register from Model empresa if the Rut field passed in POST exists already... except ObjectDoesNotExist: #...or creating a new register with sucha RUT and the field values passed in the POST new_ent = Empresa(Sujeto=Sujeto) new_ent.Name = name new_ent.Razon = Razon new_ent.Tel = Tel new_ent.Address = Address new_ent.save() return HttpResponseRedirect(.............) But I have failed a lot to make it work … -
How to run a Django method in parallel with Celery?
I have a method update_prices() on my model I would like to run in parallel with Celery but I can't figure out how to make it works. As you can see there is a problem with the .s() because it complains with 'function' object has no attribute 's'. How can i do that? This is my code: @celery.app.task(name='Update') def update(): # list of arguments exchanges_list = Exchange.objects.filter(status='ok').values_list('name', flat=True) # the function that execute the method def update_prices(name): Exchange.objects.get(name=name).update_prices() gp = group([update_prices.s(name) for name in exchanges_list])() A slightly different approach generates the same error: gp = group(update_prices.s(name) for ex in exchanges_list)() gp = group(update_prices.(name).s() for ex in exchanges_list)() Thank you -
Does this Django Migration lock MySQL table?
I have 2 tables in MySQL. Customer(contains 1 million records) PriorityCustomer(contains 3 records as of now) PriorityCustomer has a field customer which is currently a foreign key to Customer. The django model looks like this: class PriorityCustomer(models.model) customer = models.ForeignKey("Customer") ... Now I am changing the customer from ForeignKey to OneToOneField. I am only curious if this migration will lock the Customer table or not? I am using Django's own migration to do this. -
Django Forms not Showing on Web Page
Using Django 2.1.2 and Python 3.8, I have a form that I've utilized in a view, and am passing to a template. I have tried only passing through the table and not the data, I have toyed with the action field on the form. I have checked spelling and variable names, etc... Any assistance is appreciated. Here is my views.py @login_required def adm_landing_page(request): print(request.method) form = SummaryDataForm(request.POST or None) if request.method == 'POST' and form.is_valid(): formFromDate = form.cleaned_data.get('formFromDate') formToDate = form.cleaned_data.get('formFromDate') if formFromDate is not None: formFromDate.strftime('%m-%d-%Y') if formToDate is not None: formToDate.strftime('%m-%d-%Y') print(formFromDate) data = dict() raw_sql = f"EXEC EasyTrade20.dbo.spGetDashSummaryData @formFromDate = '{formFromDate}', @formToDate = '{formToDate}' " with connections['default'].cursor() as cursor: cursor.execute(raw_sql) summary_rows = cursor.fetchall() else: # below is for production when there will be 'today' transactions # raw_sql = f"EXEC EasyTrade20.dbo.spGetDashSummaryData" # below is for testing only with hard coded date to confirm there is information raw_sql = f"EXEC EasyTrade20.dbo.spGetDashSummaryData @formFromDate = '2020-05-30', @formToDate = '2020-05-30'" with connections['default'].cursor() as cursor: cursor.execute(raw_sql) summary_rows = cursor.fetchall() context = {} context['data'] = summary_rows context['form'] = form # return render(request, 'adm_landing_page.html', context={'data': summary_rows, 'form': form}) return render(request, 'adm_landing_page.html', context=context) Here is my forms.py from django import forms class SummaryDataForm(forms.Form): formFromDate = forms.DateInput() … -
how to generate a short unique id like imgur in python?
what algorithm is used to generate short unique id? for example 10 millions 7 characters id without collision. many website like "9gag.com", ifunny.co, bitly.com etc use short id for Uniform resource locator how to generate such id with few collision. -
problem while installing tenserflow on EC2 machine the process gets killed
Whenever I try to install tenserflow on my free tier eligible ec2 machine on AWS it downloads and then the further process gets killed I tried many things but didn't get any solution for the sameas you can see the tenserflow has been downloaded and then there is a keyword "killed" and the process exits -
Django: How to set a new static path in production?
working with django 3.0.5, but i guess this relates also to < django 2.0. I uploaded my first django app on my providers space, so far everything works. This is a Server Schema of my Provider... _ (` ). ( ). .-------. .-------. _( '`. ----------> | nginx | -----> | httpd | .=(`( Internet ) '-------' '-------' (( (..__.:'-' | => php via php-fpm `( ) ) | => static files ` __.:' ) | => htaccess --' | | .--------------. '----------> | Web Backends | '--------------' => per-user nginx => nodejs, python, ruby, ... => gogs, mattermost, matrix, ... However i am still do not understand some Django Static logics. My static files are served via a separate Apache service. My App called blackbird The following is like a web backend print blackbird.abc/blackbird_assets apache blackbird.abc http:8080 Ok, listening : PID 10104, vassalsuWSGI worker 2 This is like my server account dir looks like User | '-blackbird_app | '- manage.py '-hmtl <symbolic link to my documentroot> '- blackbird_assets '- static_storage '-production_static '-css '-img If i like to rename my production_static folder on my apache site to hello_static and reboot my app, django did not find the static files. Alright … -
from_db_value() takes 4 positional arguments but 5 were given Django
i have simple django notification table with the following structure +-------------------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | level | varchar(20) | NO | | NULL | | | unread | tinyint(1) | NO | | NULL | | | actor_object_id | varchar(255) | NO | | NULL | | | verb | varchar(255) | NO | | NULL | | | description | longtext | YES | | NULL | | | target_object_id | varchar(255) | YES | | NULL | | | action_object_object_id | varchar(255) | YES | | NULL | | | timestamp | datetime(6) | NO | | NULL | | | public | tinyint(1) | NO | | NULL | | | action_object_content_type_id | int(11) | YES | MUL | NULL | | | actor_content_type_id | int(11) | NO | MUL | NULL | | | recipient_id | int(11) | NO | MUL | NULL | | | target_content_type_id | int(11) | YES | MUL | NULL | | | deleted | tinyint(1) | NO | | NULL | | | emailed | tinyint(1) … -
"SMTP AUTH extension not supported by server" error while trying to send email though django app using gmail
I am trying to send a mail from my django application through gmail and i get the error saying "SMTP AUTH extension not supported by server." I have added EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USER_TLS = True EMAIL_HOST_USER = 'abc@gmail.com' EMAIL_HOST_PASSWORD = 'random' in my setting.py. Can anyone please help me figure out the solution? -
media images not being served up during production to heroku
So, I have a media folder with my profile photos in there for my users. It works fine during development locally and when debug=False on heroku, but as soon as debug=True it does not work anymore. I am not sure why. So my files are not being served up during the push and neither are they being uploaded when a user tries to upload. The image url path is there with the correct name of the image, but no photo appears and when clicking on the image url I get "The requested resource was not found on this server." My actual website is working fine. And my static images , such as my Jumbotron and navbar logo are being served up, but my media folder seems to be the issue. project dir . ├── 11_env │ ├── bin │ ├── lib │ └── pyvenv.cfg ├── Procfile ├── dating_app │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── chat.html │ ├── forms.py │ ├── media--profile_photo │ ├── migrations │ ├── models.py │ ├── static │ ├── tag.py │ ├── templates │ ├── templatetags │ ├── tests.py │ ├── urls.py │ └── views.py ├── dating_project │ ├── … -
How to update OneToOneField using Django Rest Framework
I'm trying to make an image upload through a REST API from a mobile client. I've managed to implement it using an multipart request to the REST endpoint, but when I try to update the image, the request is not handled correctly because of the constraints on the OneToOneField. This is how I implemented the API: models.py class Hotel(models.Model): name = models.CharField(max_length=500, null=False, blank=False) address = models.CharField(max_length=500, null=False, blank=False) rating = models.FloatField() owner = models.CharField(max_length=200, null=False) class Meta: ordering = ['name'] class HotelPhoto(models.Model): photo = models.ImageField(upload_to='hotel_photos', null=True) hotel = models.OneToOneField(Hotel, on_delete=models.CASCADE, primary_key=True) views.py class HotelPhotoUpload(APIView): parser_classes = [FormParser, MultiPartParser] def post(self, request): photo_serializer = HotelPhotoSerializer(data=request.data, context={'request': request}) if photo_serializer.is_valid(): photo_serializer.save() return Response(photo_serializer.data, status=status.HTTP_201_CREATED) else: logger.error(f'Error uploading image: {photo_serializer.errors}') return Response(photo_serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class HotelSerializer(serializers.HyperlinkedModelSerializer): photo = serializers.ImageField(source='hotelphoto.photo', read_only=True) class Meta: model = Hotel fields = ['url', 'id', 'name', 'address', 'rating', 'owner', 'photo'] class HotelPhotoSerializer(serializers.ModelSerializer): photo_url = serializers.SerializerMethodField() class Meta: model = HotelPhoto fields = ['hotel', 'photo', 'photo_url'] def get_photo_url(self, obj): return self.context['request'].build_absolute_uri(obj.photo.url) This is the error I'm getting: Error uploading image: {'hotel': [ErrorDetail(string='hotel photo with this hotel already exists.', code='unique')]} Bad Request: /hotels/photo/upload/ I understand this is due to the constraint on the OneToOneField since I've have already uploaded a … -
SQLite django download not showing file
I am having trouble downloading a file from my sqlite database using django. I have created a db model. i then went into my django admin and uploaded the file. Then in the index.html I set a download link. However when i press the download link my page just seems to refresh and nothing downloads. The app i have created is called chartsapp. maybe it is something to do with my line of code {{ chartsapp.the_file.url }}. i have played around with it trying the_file.url but that didn't seem to do anything either. any advice? MODELS.PY from django.db import models class Datahere(models.Model): text = models.FileField(upload_to='Uploaded') ADMIN.PY from django.contrib import admin from .models import Datahere admin.site.register(Datahere) INDEX.HTML <a href="{{ chartsapp.the_file.url }}">Download the file</a>