Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create login page using django framework?
Iam developing a project in using django framework. I need to create login page for this. How can I do this? -
i have problem when i want extend django user model
i build simple django project and i have model class is structure and i want link structure with user django in objective to give multiple access for different structure , the problem that when i make python3 manage.py make migrations all is fine and with migrate also is fine with sqlmigrate is fine but in database i don't find the Utilisateur table from immob.models import Division from django.db import models from django.contrib.auth.models import User class Utilisateur(models.Model): user=models.OneToOneField('auth.User', on_delete=models.CASCADE) Division=models.ForeignKey(Division,on_delete=models.CASCADE) MacBook-Pro-de-MAC:Invest_App mac$ python3 manage.py sqlmigrate compte 0001 BEGIN; -- Create model Utilisateur CREATE TABLE "compte_utilisateur" ("id" serial NOT NULL PRIMARY KEY, "Division_id" integer NOT NULL, "user_id" integer NOT NULL UNIQUE); ALTER TABLE "compte_utilisateur" ADD CONSTRAINT "compte_utilisateur_Division_id_191feb84_fk_immob_division_id" FOREIGN KEY ("Division_id") REFERENCES "immob_division" ("id") DEFERRABLE INITIALLY DEFERRED; ALTER TABLE "compte_utilisateur" ADD CONSTRAINT "compte_utilisateur_user_id_9142a9fe_fk_auth_user_id" FOREIGN KEY ("user_id") REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED; CREATE INDEX "compte_utilisateur_Division_id_191feb84" ON "compte_utilisateur" ("Division_id"); COMMIT; but in database i don't find UTilisateur Table ?? -
BotoCore/Boto3 Stubber Operation Not Found for generate_presigned_post
I'm trying to use the botocore.stub.Stubber to mock my boto3.client, and I am getting a botocore.model.OperationNotFoundError when trying to add the mocked generate_presigned_post response: class S3FileTestCase(TestCase): @classmethod def setUpTestData(cls): cls.s3 = botocore.session.get_session().create_client('s3') cls.region_name = 'eu-west-2' @staticmethod def _mock__get_s3(region_name): client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name=region_name) stubber = Stubber(client) stubber.add_response('generate_presigned_post', {'test':1}, {'bucket_name': 'test_bucket', 'region_name': region_name, 'object_name': 'test.csv'}) return stubber @patch('uploader.models.s3_file.S3File._get_s3', new=_mock__get_s3) def test_create_presigned_post(self): response = S3File.create_presigned_post('stuart-special-testing-bucket', self.region_name, 'test.csv') print(response) When I run test_create_presigned_post I get the OperationNotFoundError in the add_reponse. Does anyone have any idea why this might be? Note: S3File.create_presigned_post is taken directly from the docs with the only change being that the client is moved into a function so it can be mocked. -
Pycharm not able to detect django channels
I am using pycharm for django and it is not able to detect channels when i am importing it My settings files is as follow: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'dating', 'notif_sender', 'rest_framework' ] Is there any way to deal with it? -
Django-Rest-Framework Tracking not logging in user information at all
Reading through the documentation of drf-tracking I feel like I have done everything that is needed for basic tracking, but nothing is showing up in the logs area. So far what I have in in my polls\views.py app which has two models Questions and Choices from rest_framework_tracking.mixins import LoggingMixin Then in my api/views.py I have from rest_framework import generics from rest_framework.response import Response from rest_framework_tracking.mixins import LoggingMixin class LoggingView(LoggingMixin, generics.GenericAPIView): def get(self, request): return Response('with logging') But nothing is getting logged -
File download of an authenticated Django Apps from a Linux core server in Python
The question is about automating the download of data from an authenticated Django website from a Linux core server. Being able to do it with a python script will be great. Background of the question The Challenge Data website is a site proposing Data Sciences challenges. This website is written in Django. The 18-Owkin data challenge data challenge provides data of quite large size (over 10Gb). You need to be authenticated in order to download the data. I'm able to download the files from my Windows 10 laptop after authentication to the website and clicking to a download link like y_train. Downloading starts automatically in that case. However, I want to upload the data to a GPU Cloud Linux Core (without GUI) machine. I can do that from my laptop, but it is very slow as my up-going bandwidth is low. Do you see a way to get the data directly from the Linux core server? That would mean: Authenticate to the (Django) website. Then connect to the "download URL". Will it perform the download? -
Could not connect mssql with django
I am trying to connect mssql server with django. I have created a database name "sample". I have a table named "Sales" in my models.py. In my settings.py I have edited my database section as below: settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': "sample", 'USER': appsdev, 'PASSWORD': *******, 'HOST': 'xx.xxx.xxx.xx', 'PORT': 1433, 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'unicode_results': True, }, } } I have created an app named "sample_app" an in that my model.py is : from django.db import models from django_pandas.managers import DataFrameManager class Sales(models.Model): Invoice_Date = models.CharField(max_length = 20, db_column = 'Invoice Date') Sales_Value = models.CharField(max_length = 20, db_column = 'Sales Value') City = models.CharField(max_length = 60, db_column = 'City') objects = models.Manager() pdobjects = DataFrameManager() def __str__(self): field_values = [] for field in self._meta.get_fields(): field_values.append(str(getattr(self, field.name, ''))) return ' '.join(field_values) When I try make migrations, I get an error like, django.db.utils.ProgrammingError:<'42S02',"[42S02][Microsoft][ODBC Driver13 for SQL Server][SQL Server][Invalid object name ' sample_app_sales'.<208><SQLExecDirectW>"> I have set my permission for the user to "owner" level so that all are accessible for the user. I have tried "python manage.py migrate" also. But that doesn't work. The default schema for the datatbase is set "dbo". I don't … -
Using Scrapy with Celery task does not output any error
I am using Django with Celery and using Scrapy as a web scraper. My web scraper isn't not running for some reason. After some debugging I found out that there was an error with my crawler code. I have fixed that but that was when I realize scrapy isn't outputting any error logs when it an error occurs. I have been trying to get it to output logs but I can't seems to figure out where the problem is. from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings # Call crawler def crawl(url): process = CrawlerProcess(project_settings) # Specify arguments for crawler process.crawl(crawler_or_spidercls='website') print('starting....crawl') process.start() # the script will block here until the crawling is finished print('done....crawl') I have set my code to raise an error on purpose. What the celery output shows below is that it is completed successfully without the output of the error to the console. celery_worker_1 | [2019-06-21 20:22:00,655: WARNING/ForkPoolWorker-7] starting....crawl celery_worker_1 | [2019-06-21 20:22:00,666: WARNING/ForkPoolWorker-7] done....crawl celery_worker_1 | [2019-06-21 20:22:00,672: INFO/ForkPoolWorker-7] Task crawler.tasks.crawl_website[3671f518-8a41-44bc-8deb-4c8a1c5e9a6d] succeeded in 0.16195997500017256s: None celery_worker_1 | [2019-06-21 20:22:00,672: WARNING/ForkPoolWorker-7] 2019-06-21 20:22:00 [celery.app.trace] INFO: Task crawler.tasks.crawl_website[3671f518-8a41-44bc-8deb-4c8a1c5e9a6d] succeeded in 0.16195997500017256s: None However, if I ran just the crawler function by itself, I would be able to … -
Static css and images not loading in django
I am new to Django. I ran the project in Debug = True at that time all CSS and images are loading properly. I try to change Debug = False. Now I face problems. Sometimes CSS is not loading . some times images are not loading. I have two images in the folder. One is loading and the other is not loading. In Develop mode Debug = True at that time is working properly. I try to restart using python3 manage.py runserver change STATIC_URL = "../../static/" But above changes are not working Some images loaded something not loaded settings.py STATIC_URL = "/static/" STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] mysite/static/images/icon/1.png //come mysite/static/images/icon/2.png //not come both 1.png and 2.png are in folder sometimes CSS is loading. sometimes it is not loading I am using python3 manage.py runserver 0.0.0.0:5000 to start the project -
Django Forms - Validation error shown twice
I want to show up some validation errors for each fields in the form. If email already already exists If username is less than 8 characters If passwords don't match If password field is less than 8 characters forms.py class RegisterForm(forms.Form): username = forms.CharField(widget = forms.TextInput(attrs ={"class":"form-control mb-2 mr-sm-2" ,"placeholder":"username"})) email = forms.EmailField(widget = forms.TextInput(attrs = {"class":"form-control mb-2 mr-sm-2"})) password = forms.CharField(widget = forms.PasswordInput(attrs = {"class":"form-control mb-2 mr-sm-2"})) password2 = forms.CharField(label = "Confirm Password",widget = forms.PasswordInput(attrs = {"class":"form-control mb-2 mr-sm-2"})) def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password2!=password: raise forms.ValidationError("Passwords dont match") if len(password)<8: raise forms.ValidationError("Password must be atleast 8 characters long") return data def clean_username(self): username = self.cleaned_data.get('username') qs = User.objects.filter(username = username) if qs.exists(): raise forms.ValidationError("username exists") return username def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email = email) if qs.exists(): raise forms.ValidationError("email exists",code="error1") return email''' register.html <form method="POST" class="was-validated"> {% csrf_token %} <div class="form-group"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {%endif%} {{form.as_p}} </div> … -
Django - Translation default language change problem
I have two languages which is 'en' and 'tr'. In settings.py i changed the LANGUAGE_CODE to 'en'. Site loading in english this works fine. But my site url doesn't contain mysite/en and language dropdown value is not en. Both are 'tr' how can i change the default language to en? Thanks.. -
problem on delete TypeError: __init__() missing 1 required positional argument: 'on_delete'
i am working with django on pychrm, i have tested a project and everything is working, but when i tried to use another project and go back to the first project i have this error there, knowing that i have used the same version of django==1.9.5 test = models.ForeignKey(Test) TypeError: __init__() missing 1 required positional argument: 'on_delete' so where is the problem? I don't want to change anything in code, I want to change just of packages if there is a problem in package -
Why cant i write a data record without foreign-key with a model which contains a nullable foreign-key?
I have consulted the django documenation which says if you want a foreign key which can be optional you need the following options to be set on the model: on_delete=models.SET_NULL, blank=True, null=True, default=None I dropped the complete database, checked the field in MYSql admin. The field is correctly set to optinally contain NULL values. Could anyone explain why this is happening or what im doing wrong? Model: Model: class MediaImage(models.Model): class Meta: verbose_name = _("Image") verbose_name_plural = _('Image') date_created = models.DateTimeField(auto_now_add=True) date_changed = models.DateTimeField(auto_now=True, auto_now_add=False) content = models.FileField(upload_to=person_directory_path, storage=private_storage, verbose_name=_("Image")) title = models.CharField(max_length=50, verbose_name=_("Titel"), blank=True) classification = models.CharField(max_length=10, default="image") person = models.ForeignKey(Person, on_delete=models.SET_NULL, blank=True, null=True, default=None) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("User")) View: @login_required def mediafiles_add_image(request): if request.method == "POST": form = MediafilesAddImage(request.user, request.POST, request.FILES) if form.is_valid(): image_file = request.FILES['content'] if request.POST['person_id']: ImageFile = MediaImage(content=image_file, person_id=request.POST['person_id'], title=request.POST['title'], user_id=request.user) else: ImageFile = MediaImage(content=image_file, title=request.POST['title'], user_id=request.user) ImageFile.save() return redirect('mediafiles') else: form = MediafilesAddImage(request.user) return render(request, 'mediafiles/mediafiles_add_image.html', {'form': form}) return HttpResponseForbidden('Something went wrong.') The error occurs on the line: ImageFile.save() The record should be normally saved here but im getting error: AttributeError at /admin/datawarehouse/mediaimage/add/ 'NoneType' object has no attribute 'id' -
Query set with OuterRef
While the result is the expected outcome it feels like I use lots of nesting. Especially that I used Ticket and not Event for total_outstanding_revenue. I wonder if you have a better and shorter way to write that query? My query set gives me the following result: total_outstanding_revenue: <QuerySet [{'event__pk': 4, 'total_outstanding_revenue': 56000}, {'event__pk': 5, 'total_outstanding_revenue': 9000}, {'event__pk': 6, 'total_outstanding_revenue': 29000}]> Here my query set: outstanding_revenue = ( Ticket.objects.filter(pk=OuterRef('pk')) .annotate( sold_tickets=Count( 'attendees', filter=Q( attendees__canceled=False, attendees__order__status__in=( OrderStatus.PAID, OrderStatus.PENDING, OrderStatus.PARTIALLY_REFUNDED, OrderStatus.FREE ), ), ) ) .annotate( available_tickets=ExpressionWrapper( F('quantity') - F('sold_tickets'), output_field=IntegerField() ) ) .annotate( outstanding_revenue=ExpressionWrapper( F('available_tickets') * F('price_gross'), output_field=IntegerField() ) ) .values('outstanding_revenue') ) total_outstanding_revenue = Ticket.objects.filter(event__organizer=1, event__status=EventStatus.LIVE).annotate( outstanding_revenue=Subquery(outstanding_revenue)).values( 'event__pk' ).annotate(total_outstanding_revenue=Sum('outstanding_revenue', output_field=IntegerField())).values( 'event__pk', 'total_outstanding_revenue' ).order_by() -
Django: Combining two for loops
Is there a way to combine the two for loops into one? I was looking for a solution like this. But it didn't work that way: ticket_stats_by_event = { x['pk']: {'sold_tickets': x['sold_tickets'], 'available_tickets: y['avaiable_tickets']} for x, y in sold_tickets_by_event, available_tickets_by_event } The result will be: <EventQuerySet [{'pk': 6, 'organizer': 1, 'available_tickets': 20, 'sold_tickets': 2}, {'pk': 1, 'organizer': 1, 'available_tickets': 1765746, 'sold_tickets': 2116}, {'pk': 5, 'organizer': 1, 'available_tickets': 10, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'available_tickets': 60, 'sold_tickets': 4}]> Here the full function: def ticket_stats_by_event(self, organizer): sold_tickets_by_event = [ x for x in self.sold_tickets if x['organizer'] == organizer.pk ] # <EventQuerySet [{'pk': 6, 'organizer': 1, 'sold_tickets': 1}, {'pk': 1, 'organizer': 1, 'sold_tickets': 529}, {'pk': 5, 'organizer': 1, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'sold_tickets': 2}]> available_tickets_by_event = [ x for x in self.available_tickets if x['organizer'] == organizer.pk ] # <EventQuerySet [{'pk': 1, 'organizer': 1, 'available_tickets': 1721}, {'pk': 4, 'organizer': 1, 'available_tickets': 30}, {'pk': 5, 'organizer': 1, 'available_tickets': 10}, {'pk': 6, 'organizer': 1, 'available_tickets': 20}]> ticket_stats_by_event = { x['pk']: {'sold_tickets': x['sold_tickets']} for x in sold_tickets_by_event } for item in available_tickets_by_event: pk = item.pop('pk') ticket_stats_by_event[pk].update(item) return ticket_stats_by_event -
"error readlink /var/lib/docker/overlay2 invalid argument" when I run docker-compose up
I'm trying to dockerize project written in django and postgresql. What I've already done: I have environment variables stores in env_file: SECRET_KEY=value DEBUG=value ALLOWED_HOSTS=['192.168.99.100'] DB_NAME=postgres DB_USER=postgres DB_PASSWORD=postgres DB_HOST=db DB_PORT=5432 My Dockerfile: FROM python:3.7-stretch ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt /code/ WORKDIR /code/ RUN pip install -r requirements.txt COPY . /code/ My docker-compose.yml file: version: '3' services: db: image: postgres:11-alpine restart: always volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_PASSWORD: postgres container_name: "my_postgres" ports: - "5432:5432" web: build: . command: python /code/cameo/manage.py runserver 0.0.0.0:8000 volumes: - .:/code/ env_file: - env_file ports: - "8000:8000" depends_on: - db volumes: postgres_data: Please help, I don't know what I'm doing wrong. -
How to delete unnecessary import from entire project
I found some stackoverflow solution and they didn't satisfy me -- please don't recommend those link.. I have a django project with more than thousand of python file and i want to delete all the unused or unnecessary import from those file in single command. i want to delete those in just single command. is the any way to delete those? -
How to fix "Invalid password format or unknown hashing algorithm." in a custom User Model Django
models.py class UserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Please provide a valid Phone') user = self.model( phone = phone, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, phone, password): user = self.create_user( phone, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user( phone, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user phone_regex = RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}', message="Phone number should be in the format '+9999999999', Up to 14 digits allowed.") class User(AbstractBaseUser): phone = models.CharField(validators=[phone_regex],max_length=15,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.phone def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active admin.py class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('phone',) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: … -
when webdriver can’t find elem,Failed to establish a new connection
when i use WebDriverWait and can't find the elem,it reminds me urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fde08091f98>: Failed to establish a new connection: [Errno 111] Connection refused Here is my code: elem = WebDriverWait(driver,time_len).until(EC.presence_of_element_located((By.XPATH, xpath))) error: INFO isElementExist common 2019-06-21 18:32:44,099 //*[@id="phone-state"]元素查找出错 HTTPConnectionPool(host='127.0.0.1', port=39243): Max retries exceeded with url: /session/7512e5500bbe03e5d8d6490081733642/element (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fde08091f98>: Failed to establish a new connection: [Errno 111] Connection refused')) INFO isElementExist common 2019-06-21 18:32:44,100 traceback.format_exc(): Traceback (most recent call last): File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connection.py", line 160, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw) File "/usr/local/python3/lib/python3.7/site-packages/urllib3/util/connection.py", line 80, in create_connection raise err File "/usr/local/python3/lib/python3.7/site-packages/urllib3/util/connection.py", line 70, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 603, in urlopen chunked=chunked) File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 355, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/local/python3/lib/python3.7/http/client.py", line 1229, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/local/python3/lib/python3.7/http/client.py", line 1275, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/local/python3/lib/python3.7/http/client.py", line 1224, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/local/python3/lib/python3.7/http/client.py", line 1016, in _send_output self.send(msg) File "/usr/local/python3/lib/python3.7/http/client.py", line 956, in send self.connect() File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connection.py", line 183, in connect conn = self._new_conn() File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connection.py", line 169, in _new_conn self, "Failed to establish a new connection: %s" … -
dynamically add js variable value in django template url with appname and namespace
I have multiple apps in project and using appname and namespace for urls. I need to dynamically add js variable value in django template url with app name. If I write without appname like -- var temp =23 var href = "{% url 'report_page' id=0 %}".replace(/0/, temp.toString()) It is giving desired result as-- "{% url 'report_page' location_id=23 %}" But when I use appname its not working for me e.g var href = "{% url 'appname : report_page' id=0 %}".replace(/0/, temp.toString()) Let me give you the exact code: In django template: <html> <a href="{% url 'appname : report_page' id=0 %}">Report</a> </html> var href = "{% url 'appname : report_page' id=0 %}".replace(/0/, temp.toString()) In url.py of the appname: appname = 'appname' urlpatterns = [ url(r'^report-page$', views.report_page, name='report_page'), url(r'^report-page/(?P<id>[0-9]+)$', views.report_page, name='report_page'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In views: def report_page(request): import pdb;pdb.set_trace() # location_id = request.GET['id'] return render( request, 'report.html', {'id' : request.user.id, 'id' : ''} ) Note: I'm using django 1.11 and I have also tried below one but getting empty string: var temp =$('#check_id').val() <a href="{% url 'appname: report_page' %}?id="+temp;>Report</a> -
Sentry not receiving exceptions
I recently started using sentry for my Django Project. Everything was working fine in the development environment, but when i pushed it to prod, even though exception were getting thrown, but sentry wasn't reporting them on the dashboard. I tried enabling the debug setting in sentry config, and in the logs it said "Sending error event", but the event is still not being received. Can someone help with this issue? Python - 3.6.7 Sentry-sdk - 0.9.0 -
Facing connectionError in django while using ElasticSearch with docker
I am trying to load instances from my django model to the elasticsearch server but i get the error - elasticsearch.exceptions.ConnectionError: ConnectionError(: Failed to establish a new connection: [Errno -8] Servname not supported for ai_socktype) caused by: NewConnectionError(: Failed to establish a new connection: [Errno -8] Servname not supported for ai_socktype) I have established an instance of elasticsearch server using docker on my localhost on port 9200 using command - docker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:6.0.0 I am able to access the server using the curl/localhost plz help. Thanks in advance -
How to implement pagination in a Django and React App without using the rest framework?
I am working on a website whose back-end is in Django and front-end is developed using React.I want to add the pagination feature in the website but don't know how it will be implemented in the frontend part. Also I am not using REST framework to develop the back-end site. I want to know what all information I have to send to the React front-end site for this to work. How should I proceed? -
How to auto delete Web Scraper duplicate data in Django
I have a webscrapper in python. It's saving the result in a django model thus when I refresh the page it runs the webscrapper duplicating the already existing data. I tried to remove the data by using the list(dict.fromkeys (my2) ) function but no use. views.py def Scrappy(request): session = requests.Session() session.headers = { "User-Agent": 'User-Agent'} url = 'https://www.google.com/blog/' content = session.get(url, verify=False,).content soup = BeautifulSoup(content, "html.parser") obj1 = soup.find_all( 'div', {'class': 'td_module_3 td_module_wrap td-animation-stack'}) obj2 = soup.find_all( 'div', {'class': 'td_module_10 td_module_wrap td-animation-stack'}) for x in obj1: linkX = x.find('a', {'class': 'td-image-wrap'}) #saving the fetched data into variables link_x = linkX.get('href') title_x = linkX.get('title') img_src_x = x.find('img', {'class': 'entry-thumb'})['src'] link_x.replace(u"\u2019", "-") link_x.decode('utf-16', 'ignore') img_src_x.replace(u"\u2019", "-") img_src_x.decode('utf-16', 'ignore') new_Web = WebScraper() new_Web.web_title = title_x new_Web.web_url = str(link_x) new_Web.my_img = str(img_src_x) try: my = {new_Web} my = list(dict.fromkeys(my)) new_Web.save() except: pass # new_Web.save() for y in obj2: linkY = y.find('a', {'class': 'td-image-wrap'}) #saving the fetched data into variables link_y = linkY.get('href') title_y = linkY.get('title') img_src_y = y.find('img', {'class': 'entry-thumb'})['src'] img_src_y.replace(u"\u2019", "-") img_src_y.decode('utf-16', 'ignore') link_y.replace(u"\u2019", "-") link_y.decode('utf-16', 'ignore') new_Web2 = WebScraper() new_Web2.web_title = title_y new_Web2.web_url = str(link_y) new_Web2.my_img = str(img_src_y) try: my2 = ["new_Web2"] my2 = list(dict.fromkeys(my2)) new_Web2.save() except: pass # new_Web2.save() return … -
How to move a selected object in a form from one view to another?
I'm new in Django, I hope you can help me. I have a model named Derogation with 3 ForeignKey. I have 2 forms (with each one or two ModelChoiceField) spread across multiple views. In a final view, I would like to recover all these instances to create a Derogation object and save it in the database. I tried to pass the objects trough urls but i'm not sure how it works. I don't want to use the sessions. models.py class Derogation(models.Model): createur = models.ForeignKey(Createur, on_delete=models.CASCADE) individu = models.ForeignKey(Individu, on_delete=models.CASCADE) raison = models.ForeignKey(Raison, on_delete=models.CASCADE) forms.py class IndividuForm(forms.Form): individu = forms.ModelChoiceField(queryset=Individu.objects.order_by('nom'), empty_label="") class RaisonForm(forms.Form): raison = forms.ModelChoiceField(queryset=Raison.objects.all(), empty_label="") class CreateurForm(forms.Form): createur = forms.ModelChoiceField(queryset=Createur.objects.all(), empty_label="") views.py def index(request): individu_form = IndividuForm(request.POST or None) if individu_form.is_valid(): individu = individu_form() return HttpResponseRedirect('/raison/%s' % individu) #Not sure return render(request, 'derog_bv/index.html', {'individu_form':individu_form}) def raison(request, individu): raison_form = RaisonForm(request.POST or None) createur_form = CreateurForm(request.POST or None) if raison_form.is_valid() and createur_form.is_valid(): raison = raison_form() createur = createur_form() return HttpResponseRedirect('/recap/%s%s%s' %individu %raison %createur) #really not sure return render(request, 'derog_bv/raison.html', {'raison_form':raison_form}) def recap(request, individu, raison, createur): #Here I want to save my Derogation object return render(request, 'derog_bv/recap.html')