Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax not working with Apache, but same code is working with Django development server
We have a simple Ajax request that gets some table data. This method works just fine when we run it on Django development server. But when we run the same code on Apache, not even the alert before get is getting fired. We have Centos 6, Python 2.7, Apache2. There is nothing in apache error log. Any suggestions? function getStatus(){ try{ alert("Before GET..."); $.ajax({ type: "GET", url: /timer/get_status/, data: {'operater':'99'} }) .done(function(response) { alert("Response: " + response); }); }catch(err){ alert("Error: " + err.message); } } -
I tried to get the checkbox id using jquery, but it failed. i wonder what is the problem
I tried to get the checkbox id using jquery, but it failed. I do not know why, but thank you let me know what is problem I want to know what caused the problem django template(todo_list.html) {% for p in object_list %} <tr> <td> <input type="checkbox" id="{{p.pk}}" class="td_check"> </td> <td>{{p.classification}}</td> <td> <a href="" id={{p.id}} class="title_for_list"> {{p.title}} </a> </td> <td>{{p.now_diff}}</td> <!-- <td>{{p.author}}</td> --> <td> </td> </tr> {% endfor %} {% else %} <tr> <td colspan="5"> <h4>no article</h4> </td> </tr> jquery $('#todo_delete_button').click(function(e){ e.preventDefault(); // todo_check var todo_arr = []; alert("delete button") // Get checked checkboxes $('.td_check input[type=checkbox]').each(function() { if (jQuery(this).is(":checked")) { var id = this.id; alert("id : " +id) todo_arr.push(id); alert('todo_arr : ', todo_arr) } }); }) -
Django rest api DRF - ViewSet hide a field from get but include for put
I have a field that I need to hide from a get put it needs to be there for a put in a Viewset, how would I achieve this? my serialiser is as the below, the field stores data as JSON so I need to load it as JSON to perform a get. but having the original field (routing_data) there on a get will cause a 500 error, so I need to hide it from get. but when I'm using a put, it will be this field I put into. Thanks serializers.py class MonitoringSerializerRoutingTable(serializers.ModelSerializer): hostname = serializers.ReadOnlyField(source='device.hostname', ) site_id = serializers.ReadOnlyField(source='device.site_id', ) rt = serializers.SerializerMethodField(source='routing_data',) use = serializers.ReadOnlyField(source='device_use.use', ) def get_rt(self, instance): try: return json.loads(instance.routing_data) except: return instance.routing_data class Meta: model = DeviceData fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt','routing_data') views.py class MonitoringRoutingTableUpload(viewsets.ModelViewSet): queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order') serializer_class = MonitoringSerializerRoutingTable permission_classes = (IsAdminUser,) filter_class = DeviceData filter_backends = (filters.SearchFilter,) search_fields = ('device__hostname','device_use__use') -
Error H10 while deploying Django website on Heroku
I have a Django Website . It does not work on Heroku. I get this error in the logs: 2019-05-31T07:44:53.690472+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=thebigq.herokuapp.com request_id=f5737d5c-87f1-480a-8435-f69e23852990 fwd="41.45.72.141" dyno= connect= service= status=503 bytes= protocol=https This is the Procfile content: release python manage.py migrate web: gunicorn portfolio.wsgi —-log-file - I restarted the dynos, recreated app and git repositories from scratch and still getting the same error. -
When ever I login using google it always takes the username of the superuser not the current user
When ever I login using the google login it does not add new user in the auth.user but it updates the info of the superuser with the info of current user And in the social-user it does not add new user with actual username but instead it add the user with the username of superuser and rest info (email, first name and last name are of the current user). -
Facing issues after migrating my current Project to mongodb
I created my complete project in django with default(sqlite3) database and it was working fine.... Now I wish to change my database backend to mongoDB, so I used Djongo to translate my Django ORM models and queries to mongoDB document Queries I made following changes to settings.py # changing database to mongoDATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'mongo_backend', } } Now when I deleted all of my migration files and migrated changes again, Everything goes good and database mongo_backend is created in mongodb with all of my models as Collections. Most of things works fine, But there are certain issues modles.PositiveIntegerField which I was using for storing 10 digits phone number it raises validation error like Ensure this value is less than or equal to 2147483647. when I try adding user through admin interface I get NotImplementedError at /admin/auth/user/add/ UNKNOWN command not implemented for SQL SAVEPOINT "s140684618393344_x1" Is there anything which I am missing while migrating my project to mongoDB? Note : The only change in my models.py is that instead of inheriting models from django.db.models I am inheriting them from djongo.models -
Custom inclusion form tag
I have a form: class TripSearchForm(forms.Form): departure = PlaceModelChoiceField(queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url='autocomplete')) destination = PlaceModelChoiceField(queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url='autocomplete')) and I'm trying to convert this form to django inclusion tag, in order to use it a lot of times in future, also I have a view that calculated all data from form and return me proper context to render a template. Also I want to use single url for this functionality. here is my template tag, I am not sure is it right: @register.inclusion_tag('places/search_form.html') def search_form1(request): context = dict() if request.POST: form = TripSearchForm(request.POST) if form.is_valid(): departure = request.POST['departure'] destination = request.POST['destination'] return redirect('route_search', departure=departure, destination=destination) form = TripSearchForm() return {'form': form} my template: <div class="container-fluid"> <div class="row justify-content-center mt-4"> <div class="col-10"> {% load trip_search_form %} {% search_form request %} <div class="col-10 mt-5"> {% if trips %} {% for trip in trips %} {{ trip.2 }} <ul class="list-group list-group-horizontal"> {% with trip.0|first as fsegment and trip.0|last as lsegment %} <li class="list-group-item">Travel time:{{ trip.3.duration }} (hours)</li> <li class="list-group-item">Costs: {{ trip.3.cost }} (uah)</li> <li class="list-group-item">Distance: {{ trip.3.distance }} (km)</li> <li class="list-group-item"> <a href="{% url 'route_detail' fsegment.departure.slug lsegment.destination.slug trip.2 %}"> Details </a> </li> {% endwith %} </ul> <br> {% endfor %} {% else %} <h1>Trip Not Found!</h1> {% … -
How can I do to execute some functions using Django?
Hello I have a Django project but I can't achieve to execute some functions. I precise I have a file in my app by the name of file2.py and I tried this : import file2 And I got this : No module named 'file2' Could you help me please ? Thank you. -
[Help]I am unable to see 'register' after admin.site to register site in admin.py
I am trying to register my app in admin.py. I am havinfg problem with the line admin.site.register. admin.site.register from django.contrib import admin from . models import factor Register your models here. admin.site. After admin.site. 'register' is not coming or available in the list, i can't see that expected to come like this admin.site.register -
Alllow one extra filed into serializer and return validated data with that field in Django Rest Framework
I know on this topic people asked a question before but my case is different and I have implemented almost all the solutions which I found but none of them are worked for me. First I have defined three classes in models models.py class User(AbstractBaseUser, PermissionsMixin): """ User Model """ username = None email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) agency = models.ForeignKey('agency.Agency', on_delete=models.CASCADE, null=True) weekly_email = models.NullBooleanField() is_create_new_password = models.NullBooleanField(default=True) is_active = models.BooleanField(default=True) last_login_time = models.DateTimeField(null=True) last_login_from = models.CharField(max_length=255, null=True) created_at = models.DateField(default=timezone.now) updated_at = models.DateField(default=timezone.now) created_by = models.IntegerField(null=True) updated_by = models.IntegerField(null=True) """ The `USERNAME_FIELD` property tells us which field we will use to log in. In this case, we want that to be the email field. """ USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] """ Tells Django that the UserManager class defined above should manage objects of this type. """ objects = UserManager() class Role(models.Model): """ Role Model """ name = models.CharField(max_length=255, unique=True) class UserRole(models.Model): """ User Role Model """ user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) Then I have defined my serializer for user module serializers.py class RegistrationSerializer(serializers.Serializer): """ Serializers registration requests and creates a new user. """ user_id = serializers.IntegerField(required=False) email = serializers.EmailField(max_length=255) name = serializers.CharField(max_length=255) … -
How do I use webdriver with imported functions?
I have a function that opens up a webdriver session and then calls for external functions based on the input url. from externalfunctions import * def itemiser(url): regex = re.compile(r'www.(.+).com') name = regex.search(url).group(1) options = { 'a': a, 'b': b, 'c': c } if name in options: ff = webdriver.Firefox() ff.get(url) result = options[name]() ff.quit() print(result) return result functions a,b,c are in externalfuntions.py def a(): x = ff.find_element_by_css_selector('body') return x def b(): x = ff.find_element_by_css_selector('span') return x def c(): x = ff.find_element_by_css_selector('html') return x When I run this, it says that ff is not defined, obviously because the a,b,c functions can't access the webdriver. How do I do this without having to start a webdriver session every time the a,b,c functions are run. -
What's this error about while adding postgis in docker
Part of my Dockerfile is as: RUN apt-get install -yqq software-properties-common RUN add-apt-repository ppa:ubuntugis/ppa && apt-get update -yqq RUN apt-get install -yqq gdal-bin RUN apt-get install -yqq postgis I installed postgis repo, then installing postgis, but when it got to the installation step of postgis, I get this prompt on the screen & it's stuck there. debconf: unable to initialize frontend: Dialog debconf: (TERM is not set, so the dialog frontend is not usable.) debconf: falling back to frontend: Readline Configuring tzdata ------------------ Please select the geographic area in which you live. Subsequent configuration questions will narrow this down by presenting a list of cities, representing the time zones in which they are located. 1. Africa 4. Australia 7. Atlantic 10. Pacific 13. Etc 2. America 5. Arctic 8. Europe 11. SystemV 3. Antarctica 6. Asia 9. Indian 12. US Geographic area: Does anyone has any idea?? -
How to iterate values within queryset and return them to my model?
I'm trying to iterate a value in my queryset, but I have no idea where to start. I explain the case more in detail. My models. class Tarifa_Sem(models.Model): limite_inferior_isr = models.DecimalField(max_digits=10, decimal_places=2) limite_superior = models.DecimalField(max_digits=10, decimal_places=2) class Calculadora_isr(models.Model): tarifa = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, null=True, blank=True) base_gravada = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) limite_inf_calculo = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) And my queryset: def limite_inferior(self): qsl1 = Calculadora_isr.objects.values_list('base_gravada') qsl2 = Tarifa_Sem.objects.filter(Q(limite_superior__gte=qsl1) & Q(limite_inferior_isr__lte=qsl1)).distinct().values_list('limite_inferior_isr', flat=True)[0] return qsl2 def save(self, *args, **kwargs): self.limite_inf_calculo = self.limite_inferior() super (Calculadora_isr, self).save(*args, **kwargs) The problem is that I only get the calculations with the first object of my query. <QuerySet [**(Decimal('10000.00')**,), (Decimal('5000.00'),), (Decimal('1000.00'),),> Here is a more detailed model of my problem I need help to know how to pass each value through the queryset if it is already created and update the information of each record -
Django: Unable to render time changes on fullcalendar
I am trying to render event changes to my fullcalendar but my timeslots keep disappearing when the page is refreshed. I am successful when resizing or dragging events. As soon as I resize or drop my event changes in month view, my changes are saved in my database so my changes are reflected on my next refresh. The problem is when I resize and drop on day view. My time changes are reflected on my database, but when I reload the page the timeslots reverts back to all day or 12am - 1am (depending on my allDay is true or false). ''' $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, defaultView: 'month', weekNumbers: 'true', editable: true, selectable: true, eventLimit: true, // allow "more" link when too many events showNonCurrentDates: true, dayClick: function(date) { new_date = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(); var view = $('#calendar').fullCalendar('getView'); $('#calendar').fullCalendar('gotoDate',date); $('#calendar').fullCalendar('changeView', 'agendaDay'); }, events: [ {% for i in events %} { id: "{{ i.id }}", title: "{{ i.event_name}}", start: '{{ i.start_date|date:"Y-m-d" }}', end: '{{ i.end_date|date:"Y-m-d" }}', allDay: {{ i.all_day|lower }}, url: '/world' }, {% endfor %} ], eventClick: function(event, element) { event.title = "CLICKED!"; $('#calendar').fullCalendar('updateEvent', … -
Django UnicodeEncodeError when logging sql with unicode from BinaryField
Django 1.11, Python 3.5, Windows OS I have a Django model with a BinaryField. When I save an instance of the model to the database Django prints out an error message like this: UnicodeEncodeError: 'charmap' codec can't encode character '\ufffd' in position 216: character maps to <undefined> The last line of the traceback indicates that the error is occurring in django.db.backends.utils.py -- I've added a comment to the offending line: class CursorDebugWrapper(CursorWrapper): # XXX callproc isn't instrumented at this time. def execute(self, sql, params=None): start = time() try: return super(CursorDebugWrapper, self).execute(sql, params) finally: stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) ##### Error is reported from the logger.debug statement logger.debug( '(%.3f) %s; args=%s', duration, sql, params, extra={'duration': duration, 'sql': sql, 'params': params} ) So I think what's happening is that when Django tries to print the SQL insert statement it hits a non-printable Unicode character and throws an error. I don't want to disable Django debug logging while I'm developing (it is disabled in production, of course). Any way to work around this issue? -
Django_hosts integration produces 'NoReverseMatch at /en/api/' when attempting to access api
I'm in the process of integrating Django_hosts. I have the front end URLs and the admin URLs successfully integrated and working, but my REST API URLs are still inaccessible due to this error: 'NoReverseMatch at /en/api/' The error is traced to Django/urls/base.py, but I'm not sure what is triggering it: Traceback (most recent call last): File "/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) File "/lib/python3.6/site-packages/django/shortcuts.py", line 148, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "/lib/python3.6/site-packages/django/urls/base.py", line 86, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace These are my hosts.py and api_urls.py files: # hosts.py host_patterns = patterns( '', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'admin', 'Project.admin_urls', name='admin'), host(r'api', 'Project.api_urls', name='api'), ) # api_urls.py urlpatterns += i18n_patterns ( path('session_security/', include('session_security.urls')), path('', include('Project.apps.api.urls'), name='api'), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also, to kill two birds with one stone, when attempting to convert this url: {% url 'profile' request.user.id %} to this url: {% host_url 'profile' host 'www' request.user.id %} It fails throwing a NoReverseMatch … -
How to get file path dynamically in production stage?
I am doing an django application which is now running on aws ec2 instance, in that application i have one functionality for upload files to s3. While uploading s3 earlier i set folder path in settings.py from where i pick ups those files. But now on production it is difficult to go with this approach. For security reasons browser are now not allowing to get file path on file selection. Please any hint/solution would be great help. -
pytest-django won't allow database access even with mark
I'm having a difficult time figuring out what is wrong with my setup. I'm trying to test a login view, and no matter what I try, I keep getting: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. My test: import pytest from ..models import User @pytest.mark.django_db def test_login(client): # If an anonymous user accesses the login page: response = client.get('/users/login/') # Then the server should respond with a successful status code: assert response.status_code == 200 # Given an existing user: user = User.objects.get(username='user') # If we attempt to log into the login page: response = client.post('/users/login/', {'username': user.username, 'password': 'somepass'}) # Then the server should redirect the user to the default redirect location: assert response.status_code == 302 My conftest.py file, in the same tests directory: import pytest from django.core.management import call_command @pytest.fixture(autouse=True) def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command('loaddata', 'test_users.json') My pytest.ini file (which specifies the correct Django settings file): [pytest] DJANGO_SETTINGS_MODULE = config.settings I'm stumped. I've tried using scope="session" like in the documentation together with either an @pytest.mark.django_db mark, a db fixture (as a parameter to the test function), or both with no luck. I've commented out each line of the … -
How to login an existing user via Oauth2
I am having problem identifying that if a user has his account in my django app and somehow he forgets the password or he wants to login to the same account via google oauth2 authentication, so how will the work flow be? When i am trying this out then its creating a new user instead of logging in the same user to the app Please help me out with this problem. -
django web application deployment on apache server is not working with domain but accessible through server IP
I have deployed my django web application into apache server. But my problem is i can access my app through server ip, but i cant access same through server domain name. I have two django application deployed on server and i am using virtualenv and in my django settings.py file i have included server ip and domainname in allowed_hosts settings. Please find below configuration files:- 000-default.conf <VirtualHost *:80> ServerAdmin xyz@gmail.com ServerName domainname.com ServerAlias www.domainname.com DocumentRoot /var/www/html Alias /demo_shopify_python/static /var/www/html/demo_shopify_python/static <Directory /var/www/html/demo_shopify_python/static> Require all granted </Directory> WSGIDaemonProcess demo_shopify_python python-home=/var/www/html/demo_shopify_python/virtual python-path=/var/www/html/demo_shopify_python WSGIProcessGroup demo_shopify_python WSGIScriptAlias /demo_shopify_python /var/www/html/demo_shopify_python/demo_shopify_python/wsgi.py process-group=demo_shopify_python application-group=%{GLOBAL} <Directory /var/www/html/shopify_django_app-master> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /var/www/html/myproject/static <Directory /var/www/html/myproject/static> Require all granted </Directory> WSGIDaemonProcess myproject python-home=/var/www/html/myproject/myprojectenv python-path=/var/www/html/myproject WSGIProcessGroup myproject WSGIScriptAlias /myproject /var/www/html/myproject/myproject/wsgi.py process-group=myproject application-group=%{GLOBAL} <Directory /var/www/html/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =www.domainname.com [OR] RewriteCond %{SERVER_NAME} =domainname.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> https://domainname.com/myproject --> django project should display instead it is display the list of files inside the folder. https:// ip /myproject--> It's working properly. Could you please help me out to solve the issue where i am missing the point? Thanks!! -
Django front end user restrictions
I have a question which might be repeated multiple times but I'm unable to understand any of them at all. I have a view, in the view the user selects a value from a choice drop down and enters a integer amount to process. If the user enters lets say 5 in the Quantity and he has 2 leaves remaining in the selected choice, I want him to be notified after submitting the form or on the very page that you don't have this many leaves to apply for. view.py @login_required(login_url='LoginPage') def request_leave(request, emp_id): # Requesting leave employee = Employee.objects.get(employee_name=emp_id) if employee.allowed == True: form = Leave_Form(request.POST) if form.is_valid(): abc = form.save(commit=False) abc.employee_leaves = request.user.employee abc.save() form = Leave_Form context = {'employee': employee, 'form': form} # context = {'form': form} return render(request, 'projectfiles/reqleave.html', context) else: return render(request, "projectfiles/banned.html") models.py class Employee(models.Model): allowed = models.BooleanField(default=True) employee_name = models.OneToOneField(User, on_delete = models.CASCADE) employee_designation = models.CharField(max_length = 5) employee_department = models.CharField(max_length = 5) Annual_leave = models.PositiveSmallIntegerField(default=5) Sick_leave = models.PositiveSmallIntegerField(default=5) Casual_leave = models.PositiveSmallIntegerField(default=5) Half_pay = models.PositiveSmallIntegerField(default=5) Emergency_leave = models.PositiveSmallIntegerField(default=5) forms.py class Leave_Form(forms.ModelForm): to_date = forms.DateField( widget=forms.DateInput(format=('%m/%d/%y'), attrs={'class': 'form-control', 'placeholder': ' Month/Date/Year'})) from_date = forms.DateField( widget=forms.DateInput(format=('%m/%d/%y'), attrs={'class': 'form-control', 'placeholder':' Month/Date/Year'})) class Meta: model = Leave … -
django-rq Redis Client sent AUTH, but no password is set
I had my django-rq working a few days ago, but I restarted my computer and now it's not working. I can confirm redis is running with: brew services start redis Here is what I try to run to start redis: python manage.py rqworker And here is the error I get: Traceback (most recent call last): File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/casey/PycharmProjects/green_brick_django/code/pricecomparison_project/pricecomparison/maps/views.py", line 231, in get_backend_maps django_rq.enqueue(tasks.map_diffbots_backend, alexa_site_id=alexa_site.id) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django_rq/queues.py", line 226, in enqueue return get_queue().enqueue(func, *args, **kwargs) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/rq/queue.py", line 327, in enqueue at_front=at_front, meta=meta File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django_rq/queues.py", line 70, in enqueue_call return self.original_enqueue_call(*args, **kwargs) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/django_rq/queues.py", line 66, in original_enqueue_call return super(DjangoRQ, self).enqueue_call(*args, **kwargs) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/rq/queue.py", line 277, in enqueue_call job = self.enqueue_job(job, at_front=at_front) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/rq/queue.py", line 353, in enqueue_job pipe.execute() File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/client.py", line 3514, in execute self.shard_hint) File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 994, in get_connection connection.connect() File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 502, in connect self.on_connect() File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 570, in on_connect if nativestr(self.read_response()) != 'OK': File "/Users/casey/PycharmProjects/green_brick_django/venv1/lib/python3.6/site-packages/redis/connection.py", line 642, in read_response raise response redis.exceptions.ResponseError: Client sent AUTH, but no password is set I had this issue before … -
Filter out the repeated items of my queryset
In my Django project, when I query a QuerySet list, there have 5 same item unexpectedly, you can check the below snapshot. if this is a Set, there should only have two items: (SE01-A3, SE01-A4) this is my part of my test code: qs = qs.annotate(letters=Substr('name', 1, 6), length=Length('name')).order_by('letters', 'length', 'name') # you can ignore this sort code. from django.forms.models import model_to_dict for a_qs in qs: jsonstr = model_to_dict(a_qs) print(jsonstr) the output of the print(jsonstr): {'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'} {'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', … -
Does Django pyodbc support Nexus DB or is it Database dependent?
I have a project where i need to connect Nexus DB from Django application. I have tried with Django-pyodbc, DATABASES = { 'default': { 'ENGINE': "django_pyodbc", 'HOST': "nexusdb@xxx.xxx.x.xx", 'USER': "", 'PASSWORD': "", 'NAME': "testDB", 'OPTIONS': { 'driver': '{NexusDB V3.10 Driver}', 'host_is_server': True, }, } } but failed to establish connection. Can anyone help me on this ? Does Django-pyodbc support Nexus DB? Thanks -
IModuleNotFoundError: No module named 'django' in VS Code editor while no problem with terminal
I'm new to django, and want to use it in VS Code. However, "ModuleNotFoundError: No module named 'django'" blocked me. I've pip installed virtual environment, it worked fine in terminal. on terminal, it shows: (myenv) Kates-MacBook:~ kate.wang$ python3 Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> from django.shortcuts import render >>> on VS Code, it outputs: [Running] python -u "/Users/kate.wang/myenv/my_django_project/blog/views.py" Traceback (most recent call last): File "/Users/kate.wang/myenv/my_django_project/blog/views.py", line 1, in <module> from django.shortcuts import render ModuleNotFoundError: No module named 'django' My VS Code Settings are: { "workbench.iconTheme": "vs-minimal", "editor.fontSize": 15, "editor.fontLigatures": true, "terminal.integrated.fontSize": 14, "workbench.startupEditor": "newUntitledFile", "workbench.activityBar.visible": true, "python.dataScience.sendSelectionToInteractiveWindow": true, "workbench.sideBar.location": "left", "workbench.colorTheme": "Visual Studio Dark", "editor.minimap.enabled": false, "kite.showWelcomeNotificationOnStartup": false, "python.pythonPath": "python3.7", "python.venvPath": "/Users/kate.wang/myenv" } This problem has bothered me for days since I've been trying different solutions from stackoverflow and other websites the first time it poped up and didn't find a way to solve it. Thank you for your time to help me.