Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. i have installed letest postgres setup psycopg2 installed -
Django with Apache grab user from client
I have some computers into domain and I want to automatically login using Active directory credentials I've made some research over the internet and I found a module for Apache named mod_authnz_sspi. First I made a test using a PHP project and he work (I was able to grab the user from the client) but when I tried on Django doesn't work... This is my configuration Apache 2.4 ... LoadModule authn_core_module module/mod_authn_anon.so LoadModule authz_core_module module/mod_authz_dbd.so LoadModule authnz_sspi_module module/mod_authnz_sspi.so <Location "path_to_django_project"> AuthName "Test" AuthType SSPI SSPIDomain "MY.DOMAIN" SSPIAuth on SSPIOfferSSPI on SSPIAuthoritative on SSPIUsernameCase lower SSPIOmitDomain on require valid-user </Location> <VirtualHost *:80> <Directory "path_to_project"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / "path_to_wsgi" </VirtualHost> Django - settings.py MIDDLEWARE = [ ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', ... ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend ] - views.py def testing(request): user = request.META['REMOTE_USER'] return HttpResponse(user) What error I receive: Exception Type: KeyError Exception Value: 'REMOTE_USER' Sorry for my english! -
Links repeated in Django Rest Framework
this is driving me nuts! I hope you can help me. I'm trying to get 2 views for the same model (I need one just like in the model and the other one like another app needs it). I have created 2 serializers, 2 views and 2 urls but when I check they are repeated! I'll try to show you the relevant part of the code: urls.py from consumptions.routers_views import MessageViewSet, MessageSapViewSet router.register(r'messages', MessageViewSet) router.register(r'messagesforsap', MessageSapViewSet) routers_views.py from .serializers import MessageSerializer, MessageSapSerializer class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filter_fields = ['user','date','consumption','content','read', 'deleted'] class MessageSapViewSet(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSapSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filter_fields = ['user','date','consumption','content','read', 'deleted'] serializers.py class MessageSerializer(serializers.HyperlinkedModelSerializer): consumption = ConsumptionSerializer(allow_null=True) user = UserSerializer(allow_null=True) class Meta: model = Message fields = [ "id", "user", "date", "consumption", "content", "read", "deleted" ] class MessageSapSerializer(serializers.ModelSerializer): user = UserSerializer(allow_null=True) class Meta: model = Message fields = [ "user", "date", "content", "read", "deleted" ] My problem is that when I check the links in the main page of the api I find that links are repeated -
Django REST Framework, only Admin can DELETE or PUT
I'd like to ask how I can control object permissions within Django Rest Framework with the effect that: User has no ability to DELETE nor PUT Admin is a User that also can DELETE and PUT In order access API / SAFE_METHODS User must be Authenticated I have tried standard permissions, such as permissions.IsAdminUser and IsAuthenticatedOrReadOnly, but no match. Is there a standard Permission to achieve below? If not, what is the best next step, to control permissions via Django models or via DRF? | API end-points | HTTP Method | Authenticate | Permissions | Result | |---------------------- |------------- |------------ |------------ |------------------------------------------ | | /products | GET | User | User | List of product | | /products | POST | User | User | Create new product | | /products/{product_pk}| GET | User | User | Retrieve details of particular product | | /products/{product_pk}| PUT | Admin | Admin | Fully update particular product's info | | /products/{product_pk}| PATCH | User | User | Partially update particular product's info | | /products/{product_pk}| DELETE | Admin | Admin | Delete particular product's details from DB | Serializers.py class ProductSerializer(HyperlinkedModelSerializer): class Meta: model = Product fields = '__all__' views.py class ProductView(viewsets.ModelViewSet): … -
Cannot filter my Django model depence on created_date
I am trying to do a chart. My database has created_date. I am getting product data every day about 150 times and I want to see a daily increase and decrease of my data. I have no problem with my front end and Django-template (I try manual data and it works well) I just want to see the last 7 days chart. When I use Products.objects.filter(created_dates=days) filter method I am getting empty Queryset. I already try created_dates__gte=startdate,created_dates__lte=enddate it return empty Queryset to. I also try created_dates__range to there is no answer too. I just get data from created_dates__gte=days but I don't want these data. view.py from datetime import date,timedelta import datetime def data_chart(request): data = [] week_days = [datetime.datetime.now().date()-timedelta(days=i) for i in range (1,7)] for days in week_days: product_num = Products.objects.filter(created_dates=days) date =days.strftime("%d.%m") item = {"day": date,"value":len(product_num)} data.append(item) return render(request, 'chartpage.html', {'data': data}) In my database, I have thousands of data and my daily data about 150. My created_dates column format like this. created_dates col: 2020-10-19 09:39:19.894184 So what is wrong with my code?. Could you please help? -
Is mixing a class and a function based views in Djago an acceptable practice?
My project is using class based views, but I can't build a custom 500 error page using this approach. Using class based view: client_interface/views/errors/server_error_view.py: from django.shortcuts import render from django.views import View class ServerErrorView(View): def get(request): return render(request, "client_interface/errors/500.html") urls.py: from client_interface.views.errors.server_error_view import ServerErrorView handler500 = ServerErrorView.as_view() It always returns ?: (urls.E007) The custom handler500 view 'client_interface.views.errors.server_error_view.ServerErrorView' does not take the correct number of arguments (request). I've tried to change arguments of the get method to (self, request), or (*args), but the error remains the same. From the other hand if I use function based view: client_interface/views/errors/server_error_view: from django.shortcuts import render def custom_error_view(request): return render(request, "client_interface/errors/500.html", {}) urls.py handler500 = 'client_interface.views.errors.server_error_view.custom_error_view' Everything works fine. So now, I'm wondering if it's acceptable to have one function based view, and the rest of the application will be class based, or is it a crime in django world. -
401 Client Error: Unauthorized for url: https://graph.microsoft.com/v1.0/users/mehdi.aouinti@infinitymgt.fr/sendMail
401 Client Error: Unauthorized for url: https://graph.microsoft.com/v1.0/users/mehdi.aouinti@infinitymgt.fr/sendMail | Error Message: {"error":{"code":"NoPermissionsInAccessToken","message":"The token contains no permissions, or permissions can not be understood.","innerError":{"requestId":"74651b2c-4e87-4365-a1b3-b177bd5b8848","date":"2020-10-19T11:52:02"}}} -
TypeError Django at /add_items/HTML Page
Getting this error on the page : TypeError at /add_items/ str returned non-string (type NoneType) Request Method: GET Request URL: http://127.0.0.1:8000/add_items/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: str returned non-string (type NoneType) views : def add_items(request): form = StockCreateForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') z=messages.success(request, 'Successfull') print(z) return redirect("admin.home") context = { "form": form, "title": "Add Item", } return render(request, "hdm_template/add_items.html", context) Html Page: {% extends 'hdm_template/base_template.html' %} {% block page_title %} Add Item {% endblock page_title %} {% block main_content %} {% load static %} {% load crispy_forms_tags %} <section class="content"> <div class="wrapper"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Add Item</h3> </div> <!-- /.card-header --> <!-- form start --> <form method='POST' action=''> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.category|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.item_name|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.quantity|as_crispy_field }} </div> </div> <input class="btn btn-primary" type="submit" value='Save'> </form> </div> <!-- /.card --> </div> </div> </div><!-- /.container-fluid --> </section> URL: path('add_items/',HDMViews.add_items,name='add_items'), I cant understand where it went wrong -
Illegal instruction(core dumped) tensorflow python3.8 ubuntu 16
I am facing such problem Illegal instruction(core dumped) tensorflow python3.8 ubuntu 16 Python 3.8.3 (default, May 14 2020, 22:09:32) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import tensorflow as tf Illegal instruction (core dumped) -
How to speed up the execution time of sending mass emails with django EmailMultiAlternatives and get_connection method?
I'm using a mass mail function for sending mails to about 50 users. Once I sent the api call it should update the details in DB and loop the users and get the template_context based on the type of user by using EmailMultiAlternatives. Appending the results to a list and using the list to send mails by using get_connection(). The function works good. But the processing time is large because of which the function cannot send the response back within the time. def sample_function(get_request): recipient_list = [] #update DB tables for users in To_recipients: recipient_list = get_context(user) for users in Cc_recipients: recipient_list = get_context(user) success = send_mail(recipient_list) def get_context(user_type) if user_type == 'To': #some context elif user_type == 'Cc': #some context else #some context #After getting context template = render_to_string('sample.html', context=context) message = EmailMultiAlternatives(subject, message, from, to]) message.attach_alternative(template, 'text/html') return message def send_mail(mail_list): from django.core.mail import get_connection, EmailMultiAlternatives connection = connection or get_connection( username=user, password=password, fail_silently=fail_silently) return connection.send_messages(mail_list) I'm not familiar with django, please do the needful. Thanks in advance!! -
Category-SubCategory dropdown form in django
I'm a begginer in django and python . I usually using php but now I'm a little lose and I need your help . I want to do something really easy . I have a model category who can have subcategory , everything work perfectly . Now I want create a form to add a new category, still work but I want to group options by category like this Category 1 Subcategory 1 Subcategory 2 Category 2 Category 3 Subcategory 1 I don't want to download plugin ,use jquery or something too complex. I found a super tips from Simple is better than complex but something wrong . First here the code I have : I post also the function I create maybe it can help Models class Category(models.Model): title = models.CharField(max_length=100) parent = models.ForeignKey('self', null=True, blank=True,on_delete=models.SET_NULL, related_name='subcategory') def children(self): """Return subcategory.""" return Category.objects.filter(parent=self) @property def is_parent(self): """Return `True` if instance is a parent.""" if self.parent is not None: return False return True class CategoryManager(models.Manager): def all(self): """Return results of instance with no parent (not a subcategory).""" qs = super().filter(parent=None) return qs Form.py category = GroupedModelChoiceField( queryset=Category.objects.order_by('parent','title'), choices_groupby='parent', ) Field.py from functools import partial from itertools import groupby from operator … -
Django ValidationError not being raised when trying to login using an email address that does't exist
I am trying to create a simple login page where the user will input the email address and password, and django will log him/her. If not, then show "Email not found" Validation error above the form. The problem I am experiencing is that if the email address is found in the database then the user will be logged in but, if then user is not then it wont show the validation error and ultimately move to 'autheticate' function statement where since the user is 'None' will show error. I have put print statements both in my View class and clean_email function, and it can be seen from the output that the clean_email function is called and it also executes the statement in the ValidationError part. LoginView: class LoginView(View): template_name = None # gets overriden in urls.py def get(self, request, ut): form = LoginForm() ctx = { 'form' : form, 'ut' : ut, } return render(request, self.template_name, context=ctx) def post(self, request, ut): form = LoginForm(request.POST) print("the errors are", form.errors") print("the form is valid:",form.is_valid()) if not form.is_valid() : ctx = { 'form' : form, 'ut': ut, } return render(request, self.template_name, ctx) user = authenticate(request, email=form.cleaned_data['email'], password=form.cleaned_data['password'], user_type=ut) login(request, user) return redirect(reverse('home:index')) LoginForm: … -
How to check if email and password for user exists in the database and then login with these credentials?
I made CRUD operations for user in Django. Only admin can add new user with unique email and password, also can edit and delete. My question is after this how can I login them with these credentials? I was thinking to check if user exists in the database, then login him, but I can't find how to implement this. This is my basic login function, but how to improve it to check in the database? def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'Username OR Password is incorrect') context = {} return render(request, 'login.html', context -
Django query to filter all records between date plus boolean till date boolean changes
I have a model equivalent to this: class SomeModel(models.Model): reference = models.CharField(max_length=24, db_index=True) start_date = models.DateTimeField() is_active = models.BooleanField() I would like to return a queryset of all references between each reference's start-date closest to yyyy-mm-dd (i.e. specified) and is_active = True, and the date for when is_active changed to False. e.g. If I had a list: | reference | start_date | is_active | |-----------|------------|-----------| | j39djkj | 2010-12-01 | True | | dkh39d9 | 2010-11-01 | True | | j39djkj | 2010-09-01 | True | | dkh39d9 | 2010-08-01 | False | | j39djkj | 2010-05-01 | False | | dkh39d9 | 2010-03-01 | True | | j39djkj | 2010-02-01 | True | | j39djkj | 2010-01-01 | True | I want to filter by is_active = True when start_date__lte=2010-12-31 and limit the queryset response to this: | reference | start_date | is_active | |-----------|------------|-----------| | j39djkj | 2010-12-01 | True | | dkh39d9 | 2010-11-01 | True | | dkh39d9 | 2010-08-01 | False | | j39djkj | 2010-05-01 | False | I don't know the date at which the boolean changes, and the number of records is in the tens of millions with about 1 million individual … -
Hourly updated (and on table_update) view in Django/postgresql
I am looking to populate a page with active items in Django. item_active = DateTimeRangeField() Any smarter way to compare the current time: Theoretical "views.py": def time_now(): return timezone.now() def index(request): item_list = item.objects.raw('''SELECT col1, col2 FROM item_table WHERE upper(item_active) >= %s AND lower(item_active) <= %s''', [time_now]) An efficient implementation of the time comparison would be helpful, but my intuition tells me that a SQL-view updated hourly (using Django and Celery or on the PostgreSQL updated hourly and on_table_update) only containing active objects is the smartest. So for the preferred way, how do I implement the view through Django/Celery or the Datebase side? (Hourly and on_table_update) -
Unable to create list of model instances (Experiences)
I am trying to create multiple instances i.e experience for the same user but unable to do. Instead I have to hit the url twice in order to add multiple data. serialzers.py class WorkExperienceSerialzer(BaseModelSerializer): hidden_fields_to_add = {"created_by": None, "user": None} class Meta(BaseModelSerializer.Meta): model = WorkExperienceData fields = [ "company", "designation", "description", "from_date", "to_date", "reference_name", "reference_mailid", "user", "id", ] extra_kwargs = { "user": {"read_only": True}, } def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(WorkExperienceSerialzer, self).__init__(many=many, *args, **kwargs) def create(self, validated_data, **kwargs): instance = super(WorkExperienceSerialzer, self).create(validated_data) return instance def update(self, instance, validated_data): instance = super(WorkExperienceSerialzer, self).update( instance, validated_data ) return instance def get_default_value_for_field(self, field): value = super(WorkExperienceSerialzer, self).get_default_value_for_field( field ) if not value: if field == "user": value = self.context["request"].user return value views.py class WorkExperienceViewSet(ViewListUpdateDeleteViewSet, BaseModelViewSet): queryset = WorkExperienceData.objects.all() serializer_class = WorkExperienceSerialzer def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return super(WorkExperienceViewSet, self).get_serializer(*args, **kwargs) But when I am trying to pass data like below [ { "company": "something", "designation": "something", "description": "something", "from_date": "2020-10-15", "to_date": "2020-11-14", "reference_name": "something", "reference_mailid": "something@gmail.com", }, { "company": "nothing", "designation": "nothing", "description": "nothing", "from_date": "2020-10-25", "to_date": "2020-10-27", "reference_name": "nothing", "reference_mailid": "nothing@gmail.com", … -
List of items, form, response on the same page. What am I missing?
I have general.html page... In the general.html page included query_page.html... The purpose of the query_page.html is to return the list of objects, which are the buttons to detailed descriptions of themselves. It does it... Now, I'm trying to include the form into this same page with the reference to the same query_page (so on itself, so the action="" or action="{% url 'for_queries' %}")... So the result of the search will be shown on the very same page. The form searches through the list of the objects by query_id, and should return one item which matches query id of items... The form and response are easy and by the book, but I don't see the result of the search... The view function itself, it seems, doesn't react on the action... I tried to include print statements into the function, none returned in the command prompt... I see the q object in the search line and in the command prompt though... So it should be posted into the view function, but somehow it doesn't(?most likely) or the function doesn't return the result to the page... I also tried to change the view function from using request and sitting in views.py by itself … -
AttributeError after I added Select2 as a widget in one of my forms - how to fix?
I installed Django-Select2, I applied it to my project, but I'm having an error that I can't wrap my head around. Here is my forms.py file: from django.forms import modelform_factory from django_select2 import forms as s2forms from .models import Employer, JobListing, Category_JobListing class LocationWidget(s2forms.ModelSelect2Widget): search_fields = [ "location__icontains", ] def get_queryset(self): return Employer._meta.get_field("location").choices EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"], widgets={"location": LocationWidget}) JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer", "due_date", "job_application_url"]) Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"]) views.py file (only the relevant code parts): def submitJobListing(request): if request.method == "POST": employer_form = EmployerForm(request.POST, request.FILES) job_listing_form = JobListingForm(request.POST, request.FILES) category_job_listing_form = Category_JobListingForm(request.POST, request.FILES) #check if employer with that name already exists employer_name = str(request.POST.get("name", "")) #print("Employer name is \"" + employer_name + "\"") employer_with_the_same_name = Employer.objects.get(name=employer_name) #print("Length of the employer with the same name is " + str(len(employer_with_the_same_name))) employer = None if (employer_with_the_same_name != None): employer = employer_with_the_same_name if employer == None and employer_form.is_valid() and job_listing_form.is_valid(): employer = employer_form.save() job_listing = job_listing_form.save(commit=False) job_listing.employer = employer job_listing.save() category_job_listing = category_job_listing_form.save(commit=False) category_job_listing.job_listing = job_listing category_job_listing.save() #return HttpResponseRedirect(reverse("employers:thank_you")) # TODO: Add this URL and template return HttpResponse("Your form has been successfully submitted.") else: employer_form = EmployerForm() job_listing_form = JobListingForm() category_job_listing_form = Category_JobListingForm() context = { … -
django queryset union not working with only
I have 2 querysets and I am applying union on them but the strange thing is when I use only, it is selecting all fields from DB, and when I use values, it is selecting only given fields. This is selecting all fields from the Physician table doctors_models.Physician.objects.filter( appointments__member=self.context['member'] ).union(doctors_models.Physician.objects.filter( appointments__booked_by=self.context['member'] )).only('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix') BUT This is selecting only specified fields from the Physician table doctors_models.Physician.objects.filter( appointments__member=self.context['member'] ).union(doctors_models.Physician.objects.filter( appointments__booked_by=self.context['member'] )).values('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix') However, this is also selecting only specified fields but why should I define fields 2 times. doctors_models.Physician.objects.filter( appointments__member=self.context['member'] ).only('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix').union( doctors_models.Physician.objects.filter( appointments__booked_by=self.context['member'] ).only('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix')) -
how to load default values at initial and dynamically change value in highchart column?
Hey guys here I successfully made by passing dynamic value in High chart, how ever I want to render some default value first then for every submit I will pass dynamic values. Below I share my code, Please suggest guys? Let me explain this code when the page is loaded successfully, there will be form which is having three drop down box based on the value I am selecting and submitting, I will write sql query to get data from table and pass it to high chart, But I want to know how it will render before submit and after submit pass the value dyanmically. <form id ="new_form" name="new_form" method="POST"> {% csrf_token %} <label for="Question_type">Question Types:</label> <select id="qt_id" name = "select_question_type"> <option value=4>ALL</option> {% for qt in question %} <option value={{qt.id}}>{{qt.question_type}}</option> {% endfor %} </select> <label for="Certificate">Certificate:</label> <select id="Certificate" name = "select_certificate"> <option value = 0> -- Select certificate -- </option> {% for certificate in certifi %} <option value={{certificate.id}}>{{certificate.certification_name}} {{certificate.certification_year}}</option> {% endfor %} </select> <label for="state">State:</label> <select id="state_id" data-district-url="{% url 'Dashboard:load_district' %}" name = "select_state"> <option value = 0> -- Select State -- </option> {% for state in states %} <option value="{{state.id}}" >{{state.state_name}}</option> {% endfor %} </select> <input type="submit" name="submit" … -
Django rest framework [closed]
Need to know the advantages and dis-advantages of using Django rest framework. also I need open source projects examples. also examples of real platforms or projects that uses Django rest framework on production. -
Spark DataFrame.toPandas() failing on inexistent datetimes
My database source has datetimes in UTF. I'm based in CET. Loading data in a Spark dataframe and then converting the dataframe to a Pandas', results in errors due to inexistent datetimes for datetimes during change to summer time (ej: 2013-03-31 02:01:00). Ie, Pandas takes the source Spark dates as in the local timezone. Setting "timezone" to "UTC" in the Spark reader options is ignored, as setting "spark.sql.session.timeZone" to "UTC" for the application. Debugging further I've found that setting in the environment "TZ" to "UTC" manages dates correctly. However, I worry about that setting interferring in other parts of Python or my Django application. Are there other solutions I haven't found yet? If not, what other side-effects should I be aware of? Like other libraries that depend on that setting? I'm using a Windows system, with Python 3 and Django 3. -
Where the Http404 are handled exactly in django?
Where and how do the Http404 or PermissionDenied are handled exactly in django? I could not find functions or methods to catch these exceptions. -
Why 4 == 4 return false? [closed]
I don't understand why my if test failed. {% widthratio instance.child_plugin_instances|length 2 1 as forloop_half %} {% for plugin in instance.child_plugin_instances %} {% if forloop.first %} <div class="col-6"> {% endif %} {% if forloop.counter0 == forloop_half %} </div> <div class="col-6"> {% else %} "{{ forloop_half }}" "{{ forloop.counter }}" {% endif %} {% render_plugin plugin %} {% if forloop.last %} </div> {% endif %} {% endfor %} the test {% if forloop.counter0 == forloop_half %} always return False. But when I display "{{ forloop_half }}" "{{ forloop.counter }}", I got "4" "4". -
Your branch is ahead of 'origin/master' by 4 commits
I have the following error : Your branch is ahead of 'origin/master' by 4 commits. (use "git push" to publish your local commits) nothing to commit, working tree clean I have seen multiple posts on StackOverflow, but none of them work. I am trying to upload a Django Web App to Heroku for the first time. Is there a SOP for these GIT issues please ?