Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Some help, i an just a newbie
enter image description here I watched a video from codecamp but i can't setup those thing, can someone help?? -
How to set model field automatically in CreateView? (Django)
class PetAddView(CreateView): model = Pet fields = ['name','animal_type','breed','color','age','height','price','city','sex','photo'] template_name = 'pets/pet-add.html' There's my create view. My goal is to provide view with functionality to create record in database. Bu I don't need my users to specify slug instead I need to set it automatically from specified "name" value. Can I? -
How to set validation in Django model depending on fields entered?
I have the following class : class Item(models.Model): price = models.FloatField(validators=[MinValueValidator(0)]) discount = models.FloatField() The discount cannot be greater than the price. How can I do that? -
Django {{ form.as_p }} fields have pre filled values
I'm following a tutorial to create a blog website. link On part 4 he creates an "Add post" page which uses Django's {{ form.as_p }} to create a related form, However a field's value is pre-filled with the default value of that model field. I've search alot but I found no solution. How can I remove this value and show a raw field? Is it necessary to loop through the form and create a custom form? Is this a reasonable way to create a form? I heard that it's outdated and it's best models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=255) page_title = models.CharField(max_length=255, default=title) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('detail', args=str(self.id)) views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post ... class PostCreateView(CreateView): model = Post template_name = "myblog/submit_post.html" fields = ['title', 'page_title', 'body'] submit_post.html {% extends 'myblog/base.html' %} {% block title %} Create a new post {% endblock %} {% block content %} <h1>Create a new post</h1> <br> <br> <form method='POST'> {% csrf_token %} {{ form.as_p }} … -
Unable to order by multiple columns and seeing different responses of the same query on django shell and via ListAPIView
I am writing a simple chatting feature for a booking application where a customer can send messages to an owner and owner can reply to those messages. Also an owner can be a customer as well. I am storing those messages in a table which is created by this model - class CustomerOwnerMessages(BaseModel): message = models.CharField(max_length=255, blank=False, null=False) customer = models.ForeignKey( User, on_delete=models.PROTECT, blank=False, null=False, related_name="message_from_customer", ) owner = models.ForeignKey( User, on_delete=models.PROTECT, blank=False, null=False, related_name="message_to_owner", ) My task is to get the list of customers who has so far exchanged the messages with the logged in owner. Let say the pk of that owner is 1. So first I planned to get the object of User model like this - owner = User.objects.get(pk=1) Then I decided to get all the messages of this user sent or received as an owner from model CustomerOwnerMessages. Please note that I have defined related_name for each foreign key in the same model. messages = owner.message_to_owner.filter() I have the list of all the instances of messages sent by this owner. Now I just want the list of all the unique instances where the combination (owner, customer) isn't repeated. So I decided to order_by the messages … -
Django LDAP - raised SIZELIMIT_EXCEEDED
Django application can connect to the LDAP server flawlessly. While login I'm getting the below error, search_s('DC=xx,DC=yyy,DC=com', 2, " (objectClass=organizationalPerson)") raised SIZELIMIT_EXCEEDED(('msgtype': 100, 'msgid': 2, 'result': 4, 'desc': 'Size limit exceeded', 'ctrls': []}) How to set the SIZELIMIT in LDAP configuration please help me with this issue. My settings.py, # Baseline Configuration AUTH_LDAP_SERVER_URI='Ldap://xyz.server.com' AUTH LDAP CONNECTION OPTIONS = { ldap.OPT_REFERRALS: 0 } LDAP_IGNORE_CERT_ERRORS = True AUTH_LDAP_BIND_DN = 'CN=dev,OU=Accounts,DC=xy,DC=qwerty, DC=com' AUTH_LDAP_BIND_PASSWORD = 'qwerty123' AUTH_LDAP_USER_SEARCH = LDAPSearch( 'DC=xy,DC=qwerty, DC=com', ldap.SCOPE_SUBTREE, "(objectClass=organizationalPerson)", ['cn'] ) LDAP_USER_ATTRIBUTES="cn,sn,givenName,displayName,employeeID,mail" LDAP_BASE_DN = "DC=xy,DC=qwerty, DC=com" LDAP USE SSL= True LDAP_SEARCH_DOMAINS = "au.pbs,branch1,branch?" AUTH_LDAP_GROUP BASE = "OU=Accounts,DC=xy,DC=qwerty, DC=com" AUTH_LDAP_GROUP_FILTER = '(objectClass=posixGroup)' AUTH LDAP GROUP SEARCH = LDAPSearch( AUTHLDAP_GROUP_BASE, ldap.SCOPE_SUBTREE, AUTH LDAP GROUP FILTER ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType (name_attr="cn") AUTH_LDAP _USER_ATTR_MAP = { 'first name': 'givenName', "last name': 'sn', 'email':'email' } -
Testing a Class method with sessions using Mock in Django
I am new to Django testing and I am slowly getting to grips with Client() and RequestFactory based requests, but I am completely stumped as to how to test the following code correctly. (login is required through the OTPRequiredMixin) class EmailVerificationCode(OTPRequiredMixin, FormView): def time_diff(): # A simplification for the purpose of my question return True def check_code(self): try: if self.time_diff(): if str(self.user_code) == str(self.code): user_record = User.objects.get(pk=self.request.user.pk) user_record.is_user_verified = True user_record.save() messages.success(self.request, _('Your email has been verified - thank you' )) return redirect(reverse('account:user_profile')) else: messages.error(self.request, mark_safe(_( 'Sorry, but your code did not match.' ))) return redirect(reverse('account:verify_email_code')) else: messages.info(self.request, mark_safe(_('Sorry, but your code has expired.<br>' ))) return redirect(reverse('account:verify_email')) except (AttributeError, ObjectDoesNotExist): messages.warning(self.request, mark_safe(_('We are very sorry, but something went wrong. 'Please try to login again' ))) return redirect(reverse('two_factor:login')) This is what I have tried so far: I have successfully mocked the "if time_diff()" to return False, together with the ability to test the user_code/code permutations, using something like: self.view = EmailVerificationCode() self.view.time_diff = Mock(return_value=False) self.view.user_code = '0000000000' self.view.code = '0000000000' self.view.check_code() Which is where I have reached the level of my 'incompetence', as I cannot workout how to test: user_record = User.objects.get(pk=self.request.user.pk) This test requires that I mock a session variable … -
Call template tag linebreaksbr Django in views
How can I use the linebreaksbr template tag in views.py? I've tried in the view but the result is the tag is read as a string. i am displaying data from database by using ajax jquery which is called via html id tag. How can i use the linebreaksbr tag template on the data if using ajax jquery? This is my views.py to call the data. data_row = { 'title' : data_list['title'], 'image' : data_list['image'], 'company' : data_list['company'], 'location' : data_list['location'], 'requirement' : linebreaksbr(data_list['requirement']), 'datetime_posted' : 'Posted ' + formatted_date + " by " + jobsite, 'link' : link, 'detailModelId' : 'detailModel-' + str(i), } data.append(data_row) i += 1 but if i add linebreaksbr in this views, the result is like this enter image description here And this is my ajax jquery <script> $(document).ready(function() { var timer = null; refresh(); $('#keywordTitle, #keywordLocation').keydown(setTimer); $('#check_hari_1, #check_hari_3, #check_hari_14, #check_hari_30').change(setTimer); $('#cat_all, #cat_jobstreet, #cat_kalibrr, #cat_glints').change(setTimer); $(document).on('click', 'a.page-link', function(evt) { evt.preventDefault(); $('#page').val($(this).data('page-number')); history.pushState({}, null, $(this).attr('href')); refresh(); }); function setTimer() { clearTimeout(timer); timer = setTimeout(refresh(), 2000); } function refresh() { s = $('#spinner').clone(); s.removeClass('d-none'); s.appendTo('#job_list'); $.ajax({ url: "/home/jobs-search-api/", method: 'POST', data: { 'page': $('#page').val(), 'keywordTitle' : $('#keywordTitle').val(), 'keywordLocation': $('#keywordLocation').val(), 'check_hari_1': $('#check_hari_1').is(':checked'), 'check_hari_3': $('#check_hari_3').is(':checked'), 'check_hari_14': $('#check_hari_14').is(':checked'), 'check_hari_30': $('#check_hari_30').is(':checked'), … -
Send Email with a Fixed IP in Python
I am working on Project which requires me send email from IP of specific region Only. So What I trying to achieve is I am having IP address of different region. Suppose I want to send email in India I will select IP that has Geo Location of India and send/Reply to Email Using Python smtplib. Kindly help on how to achieve this -
how to custom search using post method in django
I am the new in django. My problem is that I want to do search with URL like http://127.1.8000/shop/search/queryask pattern I don't want to use with query with question mark like ?q=abcd Can any body guide me that how to do this in url,view and django template files. Thanx -
Django ManyToMany relationship(Movie and Genre) - adding a movie object to a genre
I am developing a streaming website. When you upload a movie it gets the genres related to that movie from an API. If the genres are not in the Genre table, they are added in the UploadMovie view. When these genres are added to the table, I am adding the Movie those genres are for with on the last line in the code below. Example given: If I upload the movie: Die Hard 1, which has the following genres: Action, Thriller, those genres are added to the DB, if they doesn't exist already. During the creation of each genre, Die Hard is added to the genre relationship with: genre_to_save.movies.add(Movie.objects.last()) - this should put the movie Die Hard under the genres, action and thriller and it indeed does. However when I check the database, I see that Die Hard is also under every other genre that it is NOT, like Fantasy and Science Fiction. Die Hard is movie object(34) I am sure that I have some flaw in my function view UploadMovie, but I dont know where. Thank you in advance. class UploadMovie(View): def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/accounts/login') else: return render(request, 'core/video_upload.html') def post(self,request,*args,**kwargs): form = … -
django: CourseNote() got an unexpected keyword argument 'user'
i am writing a function to save notes to the database from a form but it keeps throwing this error CourseNote() got an unexpected keyword argument 'user' and i dont seem to know where this error is coming from. view.py def CourseNote(request, course_slug): course = Course.objects.get(slug=course_slug) user = request.user if request.method == "POST": course = Course.objects.get(slug=course_slug) user = request.user note_title = request.POST.get('note_title') note_content = request.POST.get('note_content') # CourseNote.objects.create(user=user, course=course, note_title=note_title, note_content=note_content) new_note = CourseNote(user=user, course=course, note_title=note_title, note_content=note_content) new_note.save() response = 'Saved' return HttpResponse(response) urls.py path('<slug:course_slug>/save-note', views.CourseNote, name="save-note"), models.py class CourseNote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="note_user") course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) note_title = models.CharField(max_length=200, blank=True, null=True) note_content = models.TextField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) -
Convert a raw self join sql to Django orm code (no internal foreign key)
I have Article and Tag models, having a many to many relation through another model of ArticleTag. I want to find that for a given tag "Health", how many times it's been simultaneously with other tags on articles. (e.g. on 4 articles with tag "Covid", on 0 articles with tag "Infection" , etc) I can perform a self join on ArticleTag with some Where conditions and Group By clause and get the desired result: SELECT tag.title, COUNT(*) as co_occurrences FROM app_articletag as t0 INNER JOIN app_articletag t1 on (t0.article_id = t1.article_id) INNER JOIN app_tag tag on (tag.id = t1.tag_id) WHERE t0.tag_id = 43 and t1.tag_id != 43 GROUP BY t1.tag_id, tag.title However I want to stay away from raw queries as much as possible and work with Django QuerySet APIs. I've seen other threads about self join, but their model all have a foreign key to itself. Here are my Django models: class Tag(Model): ... class Article(Model): tags = models.ManyToManyField(Tag, through=ArticleTag, through_fields=('article', 'tag')) class ArticleTag(Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE)) article = models.ForeignKey(Article, on_delete=models.CASCADE)) -
Django rest serializer how to use different versions of saved images?
Всем привет! У меня возник вопрос при работе с изображениями. Я переопределил метод save в моделях, для того чтобы сохранять несколько версий изображения. Теперь я хочу в Сериализаторе использовать вторую сохраненную версию изображения, с измененными пропорциями. Подскажите, пожалуйста, как я могу это сделать и возможен ли такой сценарий? models.py def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image) thumbnail_size = (500, 500) img.thumbnail(thumbnail_size) image_name, image_ext = os.path.splitext(self.image.path) custom_path1 = '{}_500{}'.format(image_name, image_ext) img.save(custom_path1, "JPEG", optimize=True, quality=75) -
How to fix CORS - same domain, Django API and React site
I have a page developed in React deployed with vercel, which makes requests to a Django web server. I've put them under my domain: one is page.example.com and the other is api.example.com. However, when the page makes requests to api.example.com I get a CORS error. Moreover, the pre-flight gives a 401 Unauthorized, even though the request uses the right authorization token. The request works in performed in Postman. -
How to do pagination for a serializer field?
I have a task where I need to get stats and feedback by moderator ID. The 'stats' field is general, the 'feedback' field is a list of feedbacks. Can I make pagination for 'feedback' field? Of course I can make different endpoints for stats and feedback, but I'm not allowed to do this. // GET /api/moderators/:id/feedback { "stats": [ { "name": "123", "value": -10 } ], "feedback": [ { "id": 1, "createdBy": "FN LN", "createdAt": "DT", "comment": "", "score": 5, "categories": [ { "name": "123", "status": "POSITIVE/NEGETIVE/UNSET" } ], "webinarID": 123456 }, { ... } ] } views.py class TeacherFeedbackViewSet(ViewSet): permission_classes = [IsAuthenticated, TeacherFeedbackPerm] renderer_classes = [CamelCaseJSONRenderer] @base_view def list(self, request, pk): moderator = get_object_or_404(Moderator, pk=pk) serializer = ModeratorFeedback(moderator) return Response(serializer.data) serializers.py class TeacherFeedbackSerializerDetail(ModelSerializer): created_at = DateTimeField(source='datetime_filled') created_by = SerializerMethodField(method_name='get_created_by') categories = SerializerMethodField(method_name='get_categories') webinar_id = IntegerField(source='webinar.id') moderator_id = IntegerField(source='moderator.id') class Meta: model = TeacherFeedback fields = ['id', 'created_by', 'created_at', 'categories', 'score', 'comment', 'moderator_id', 'webinar_id'] def get_categories(self, feedback: TeacherFeedback): data = [] category_names = list(FeedbackCategory.objects.all().values_list('name', flat=True)) for category in feedback.category.all(): z = TeacherFeedbackCategory.objects.get(category=category, feedback=feedback) data.append({"name": z.category.name, "status": z.status}) unset = list(map(lambda x: {"name": x, "status": "unset"}, list(set(category_names) - set([i["name"] for i in data])))) return sorted(data + unset, key=lambda x: x["status"]) def … -
Restart Nginx not effect with Uvicorn
I deployed my Django API project using Nginx and Uvicorn over HTTPS, everything is operating fine, but if I tried to change anything in the source code like adding new features or updating the settings, it does not make affect the server and there are no errors that come across as well! I ensured that I made a change to sensitive stuff in settings.py, restart the Nginx and Supervisor sudo service supervisor restart sudo service nginx restart Nginx server { listen 443 ssl; server_name thebeauwow.me; ssl_certificate beauwow_ssl.crt; ssl_certificate_key beauwow_ssl_private.crt; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; charset utf-8; client_max_body_size 1G; access_log /var/log/nginx/mysite.com_access.log; error_log /var/log/nginx/mysite.com_error.log; location /static { alias /home/beauwow/The-Beau-Wow-Project-BE/static/; } location /media { alias /home/beauwow/The-Beau-Wow-Project-B/media; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_buffering off; proxy_pass http://uvicorn; } } upstream uvicorn { server unix:/tmp/uvicorn.sock; } supervisor ; supervisor config file [unix_http_server] file=/var/run/supervisor.sock ; (the path to the socket file) chmod=0700 ; sockef file mode (default 0700) [supervisord] logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) childlogdir=/var/log/supervisor ; ('AUTO' child log dir, default $TEMP) ; the below section must remain in the config file for RPC ; (supervisorctl/web interface) to work, additional … -
How to restart Nginx server with Github Action yaml file
I am working on a Django project, I am new in Github Action, I had set up Github action file name: Django CI on: push: branches: [ master ] jobs: build: runs-on: self-hosted steps: - uses: actions/checkout@v3 - name: Install Dependencies run: | virtualenv -p python3 env . env/bin/activate pip3 install -r requirements.txt My file get uploaded but issues is that I had to restart the Nginx server, How I can Restart Nginx server -
How to fix an Sending E-mail error in Django
Im getting an error trying to send an e-mail trough Django that I need to solve it I get this error with this settings.py: "getaddrinfo failed" if DEBUG: EMAIL_HOST = 'stmp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = 96274717 # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' and I get this error with this setting.py ConnectionRefusedError at /django-store-account/register/ I need to find a way to fix sending e-mail in Django for me to verify the accounts if DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = 96274717 # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' my urls.py: path('register/', views.account_register, name='register'), views.py: def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email_body = message email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = … -
Using Django Channels (websocket layer consumer) to update a webpage with data from an internal database and external an data source
I have the following django channels class which updates values on a webpage webpage. The class receives data from screen clicks, performs actions (toggling indicdual relays or setting a series of them for a particular use, updates a databse and then updates the webpage via a websocket layer. All this worked fine until I introduced nina. This receives data from a remote source via a curl POST (see below). A curl POST results in the fail: 'TypeError: nina() missing 1 required positional argument: 'request', but if I drop 'self' I don't see how I can call 'update_relays' using its data. import logging import json from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import dbConditions, dbRelays logger = logging.getLogger(__name__) class DomeControlConsumer(SyncConsumer): """#from https://channels.readthedocs.io/en/latest/topics/consumers.html""" def websocket_connect(self, event): """Connects to webpage""" logger.debug("connected - Event: %s", event) async_to_sync(self.channel_layer.group_add)( "dome_control_group", self.channel_name ) # make the group layer for signals to send to self.send({ "type": "websocket.accept" }) self.build_and_send_context() def websocket_receive(self, event): """recives button presses from webpage either 'control_button' or relays 1 through 8""" logger.debug("received: %s from %s", event, event["text"]) self.update_relays(event["text"]) # if the control button was pressed or if a relay button is pressed def websocket_disconnect(self, … -
Adding container commands to elastic beanstalk breaks deployment
I have a django web app hosted via elastic beanstalk Due to the fact that ./platform/hooks/postdeploy migrate command seems to no longer bee working (Django migrations no longer running on aws) I have tried to use container commands in my django.config file instead container_commands: 00_test_output: command: "echo 'testing.....'" 01_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py migrate --noinput" leader_only: true This, however, provokes the error on deployment: 2022-05-25 08:03:36 WARN LoadBalancer awseb-e-g-AWSEBLoa-Q8MLS7VPZA00 could not be found. 2022-05-25 08:03:36 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. This error occurs even if only the 00_test_output command is included. Does anyone have an idea as to why the loadbalancer cannot be found when container commands are added? -
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: table customer_ordermod el has no column named created_on
I want to build a food delivering app, but facing this error. "return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: table customer_ordermod el has no column named created_on" this is the view.py from ast import Return from multiprocessing import context from django.shortcuts import render from django.views import View from .models import MenuItem, Category, OrderModel class Index(View): def get(self, request, *args, **kwargs): return render(request, 'customer/index.html') class About(View): def get(self, request, *args, **kwargs): return render(request, 'customer/about.html') class Order(View): def get(self, request, *args, **kwargs): # get every item from each category appetizers = MenuItem.objects.filter( category__name__contains='Appetizer') main_course = MenuItem.objects.filter( category__name__contains='Main Course') desserts = MenuItem.objects.filter(category__name__contains='Dessert') drinks = MenuItem.objects.filter(category__name__contains='Drink') # pass into context context = { 'appetizers': appetizers, 'main_course': main_course, 'desserts': desserts, 'drinks': drinks, } # render the templates return render(request, 'custormer/order.html', context) def post(self, request, *args, **kwargs): order_items = { 'items': [] } items = request.POST.getlist('items[]') for item in items: menu_item = MenuItem.objects.get(pk=int(item)) item_data = { 'id': menu_item.pk, 'name': menu_item.name, 'price': menu_item.price } order_items['items'].append(item_data) price = 0 item_ids = [] for item in order_items['items']: price += item['price'] item_ids.append(item['id']) order = OrderModel.objects.create(price=price) order.items.add(*item_ids) context = { 'items': order_items['items'], 'price': price } return render(request, 'customer/order_conformation.html', context) this is my model.py from time import strftime from unicodedata import category, name from … -
(Django jwt token) get specific user with user id
Current I am retrieving user data with the UserViewSet like this: class UserViewSet(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticated,) What I did was to make a GET request the via the endpoint `http://localhost:8000/account/auth/user/${id}` together with a Bearer jwt Token on the header. However, I realized that I can get the all the user with the same jwt token because of the Account.objects.all(), which is not I wanted at all. I want to get the specific user corresponding to their id with their unique jwt token. Anyone has an idea how to do it? Thanks a lot. -
psycopg2 NotNullViolation on column "ip" for Django/Gunicorn/Nginx system
I have a Django system that has gunicorn hosting the dynamic content and nginx the static, nginx passing through to gunicorn as required via a Unix socket. Every request that requires static content is generating an error like that below. Is this because the request comes from a Unix socket and not via IP? How do I fix this? A Quick "Google" hasn't helped but perhaps I've not found the right question yet :-(. django.db.utils.IntegrityError: null value in column "ip" violates not-null constraint DETAIL: Failing row contains (48, 302, GET, /, 2022-05-25 07:51:28.855717+00, f, f, null, , Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KH..., en-GB,en;q=0.9,en-US;q=0.8,mt;q=0.7, null). Thanks for any suggestions. -
MongoDB driver to support most Django functionality
As per the project requirment, I have to use Django + MongoDB. I am super new to Django (not good in Django's ORM too) but have good experience with MongoDB. My project is about storing a lot of Schemaless data and then making analysis reports or use for machine learning etc. MongoDB states PyMongo as official driver for Python projects but, there are bunch of other drivers also available like mongoengine, djongo, motor etc. After reading a lot of articles, still I can't find simple answer to my question: WHICH DRIVER SUPPORT MOST OF DJANGO FUNCTIONALITY About Djongo, This link states that: because it supports all django contrib libraries. Using Djongo, all we need to do is setting up and changing the models base import, no need to worry about changing serializers, views, and all other modules. If I use PyMongo, will I miss any advantage of Django except ORM? I am open for suggestions and critisism as i just started learning this...