Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
from django_extensions.db import UUIDField ImportError: cannot import name UUIDField
i'm trying to fix a problnme regarding UUIDField. While running myb ./manage.py it shows up it cannot import UUIDField this is the model i'm using. from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django_extensions.db import UUIDField from django_extensions.db.fields import UUIDField class Text_Message(models.Model): send_date = models.DateTimeField(null=True, blank=True, editable=False) delivery_date = models.DateTimeField(null=True, blank=True, editable=False) uuid = uuidfield.fields.UUIDField(auto=True, help_text=_('Used for associating replies.')) -
Getting Improperly Configured error while running Django server
I'm trying to configure Django and on running: python manage.py runserver, it runs the server correctly but when I go to http://127.0.0.1:8000/, it gives me the following error: File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__ self.load_middleware() File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 45, in load_middleware mw_class = import_by_path(middleware_path) File "/usr/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_by_path sys.exc_info()[2]) File "/usr/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 21, in import_by_path module = import_module(module_path) File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module __import__(name) ImproperlyConfigured: Error importing module django.middleware.security: "No module named security" Don't know what the problem is but on looking on the internet, I found something about having issue with middleware ordering. So here's my middleware in my settings.py file: MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] How to solve this error? -
CELERY 4.0.2 doesn't log into the file
I'm using Celery (celery==4.0.2) in my Django project. The problem is that I can't make Celery log into the file. I've tried everything. The only thing which works is to specify the file in the command: celery worker -A realestate_scanner -l info --purge --logfile=logs/celery.log But the problem is that log can became very huge so I need to specify rotating logger and I want to run worker and beat as a deamons in production. realestate_scanner/realestate_scanner/celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'realestate_scanner.settings') app = Celery('realestate_scanner') app.config_from_object('django.conf:settings',) app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) realestate_scanner/realestate_scanner/settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'djmoney', 'storage', 'engineapp', 'presentation', 'import_export' ] BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Bratislava' CELERY_LOG_FILE = 'test.log' # Not working worker_log_file = 'test.log' # Not working worker_hijack_root_logger = False LOGGING = { # Not working 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'simple': { 'format': '%(levelname)s %(message)s', 'datefmt': '%y %b %d, %H:%M:%S', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'celery': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', … -
Unable to de-localize decimal value in form
I have a form input price. As you'd expect, it's a decimal, and the <input type="number"> doesn't enjoy wide cross-browser compatibility with using , as a decimal separator character. price = forms.DecimalField( label=_("Price"), required=True, localize=False, # prevent displaying decimal place as ',' widget=forms.NumberInput(attrs={ 'step': 0.01, 'min': 0, "class":"form-control", "placeholder": _("Two decimal places"), })) Specifically, when rendering this field in an update view, if the server returns a price of 20,00 nothing will be displayed in the widget. I hence tries to use the localize kwarg to the field as per here. This isn't working though; the server is still sending through a localized separator and the page doesn't work with most European languages. Here's what renders: <input step="0.01" min="0" class="form-control" id="id_price" name="price" placeholder="Deux décimales" required="" value="20,00" type="number" > How do I fix this problem? -
Query that returns a multi dimensional collections with a particular criteria
Can anyone help me how to query this certain problem? here is an example model: class Diagnosis(models.Model): is_success= models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) Here is the implementation: d1 = Diagnosis.objects.create(is_success = False) d2 = Diagnosis.objects.create(is_success=False) d3 = Diagnosis.objects.create(is_success=True) d4 = Diagnosis.objects.create(is_success=False) d5 = Diagnosis.objects.create(is_success=False) d6 = Diagnosis.objects.create(is_success=False) d7 = Diagnosis.objects.create(is_success=True) Now what i would like to filter is returns a multi dimensional collection(array) from the is_success=True to its previous is_success=False: I am struggling to get this output example: [ [d1(False), d2(False), d3(True)], [d4(False), d5(False), d6(False), d7(True)] ] -
Persistent library instead of repeated imports django
I'm using Django to host a machine learning service, which returns predictions when queried with the parameters. My problem is, everytime a new request comes in, it has to import tensorflow and all the various libraries all over again. This makes it really slow. Is there a way to make the libraries and models persistent? Current Architecture (Only that service): main_app/ manage.py classifiers/ __init__.py util.py views.py lstm_predictor.py util.py: (Tensorflow is reloaded everytime a new request comes in!) from sklearn.externals import joblib import pandas as pd import xgboost as xgb from keras.models import load_model from keras.preprocessing import sequence from nltk.corpus import stopwords import os,calendar,re import logging from lstm_predictor import lstm_predict logger = logging.getLogger(__name__) # Load models here to avoid reload every time ensemble_final_layer = joblib.load("final_ensemble_layer.pkl") text_processor = joblib.load("text_processor.pkl") lstm = load_model("LSTM_2017-07-18_V0") Is there somewhere I can shift the imports to, so that its only loaded once when the app starts? Thank you! :) -
Modify ImageField upload_to method to work dynamically
I want to set up in my rest service upload_to method in ImageField dynamically for creating sub-folders in /MEDIA/, that will be called "{0}_{1}".format(user_id, task_id). File and task_id are going from POST request. For now those variables needed to create sub-folders are empty. I'm quessing that I can not utilize task_id while instance is not saved. Question is how can I create my sub-folders? Example request looks like that: { file_location: binary_file, task_id: 15 } serializers.py class PostProcessingRawFilesSerializer(serializers.ModelSerializer): class Meta: model = ProcessingRawFilesItem fields = ( 'id', 'file_location', 'task_id' ) def create(self, validated_data): task_id_data = validated_data.pop('task_id') task = Task.objects.get(pk=task_id_data) raw_image = ProcessingRawFilesItem(task_id=task, **validated_data) return raw_image models.py def user_directory_path(instance, filename): task_id = instance.task_id user_id = Task.objets.get(pk=task_id).owner_id return '{0}_{1}/{2}'.format(user_id, task_id, filename) class ProcessingRawFilesItem(models.Model): id = models.AutoField(primary_key=True) file_location = models.ImageField(upload_to=user_directory_path) task_id = models.ForeignKey(Task, related_name='processing_raw_files', on_delete=models.CASCADE, null=True, blank=True) Thanks in advance! -
celery eats up memory
I have a t2.medium instance on aws. Where two of my python applications and their celery workers runs inside separate docker containers. Total 4 containers are running. For no reason, celery eats up lots of memory of instance. Screenshot of ps command output I have checked that django is running with DEBUG_MODE False. I have configured worker_max_tasks_per_child to 200 and worker_max_memory_per_child to 200MB. I have: Ubuntu Version: 16.04 Python Version: 3.5 As of now I am not running any tasks, still it eats up instance memory. Kindly help me debugging the problem. -
django queryset for grouping and counting
Details.objects.all() Dept Gender Shift Software Male Day Software2 Female Night what i want is json like {"Gender":"Male", "count":2} using queryset im new to djnago and have tried this Details.objects.values("Gender").annotate(count=Count("Gender")).order_by("Shift") where i get [{'count': 3, 'Gender': u'Female'}, {'count': 1, 'Gender': u'Male'}, {'count': 3, 'Gender': u'Female'}, {'count': 3, 'Gender': u'Male'}] of both departments...I want one dept at a time(Software/Software2). Please help:) Thanks. -
Pass a variable to the next template
I want to pass one variable throuth one template to another. First template I identify the variable and go to the second. From second I want to pass this variable to the third template. valoare-list.html {% for valoare in valoares %} <a href="{% url 'valoare_detail' pk=valoare.pk %}"> Contracte de valoare {{ valoare.tip_valoare }} </a> {% endfor %} valoare-detail.html <!-- This variable to be sent to the next template --> Valoare: {{ valoare.tip_valoare }} <br> {% for tip in tips %} <a href="{% url 'contract_list' valoare=valoare.tip_valoare pk=tip.pk %}"> Tip Contracte de {{ tip.tip_contract }} </a> {% endfor %} contract-list.html Valoare: {{ valoare.tip_valoare }} <br> Tip Contract: {{ tip.tip_contract }} models.py from django.db import models class Valoare(models.Model): VALOARE_CHOICES = ( ("MICA","mica"), ("MARE","mare"), ) tip_valoare = models.CharField(max_length=4, choices=VALOARE_CHOICES, default="MICI") file_name = models.FileField(null=True, blank=True) def __str__(self): return self.tip_valoare class Tip(models.Model): TIP_CHOICES = ( ("BUNURI","bunuri"), ("SERVICII","servicii"), ("LUCRARI","lucrari"), ) tip_contract = models.CharField(max_length=8, choices=TIP_CHOICES, default="BUNURI") file_name = models.FileField(null=True, blank=True) def __str__(self): return self.tip_contract views.py from django.shortcuts import render, get_object_or_404 from .models import Valoare, Tip def valoare_list(request): valoares = Valoare.objects.all return render(request, 'contracte/valoare_list.html', {'valoares': valoares}) def valoare_detail(request, pk): valoare = get_object_or_404(Valoare, pk=pk) tips = Tip.objects.all return render(request, 'contracte/valoare_detail.html', {'valoare': valoare, 'tips': tips}) def contract_list(request, valoare, pk): (?????) tip … -
easy_thumbnails on Django produces bad images (greyscale and pixelated) from PNG but not JPG source images
I am running Django 1.8 on Ubuntu 14.04 in an Apache server hosted with GoDaddy. Other libraries used are materializecssform, ckeditor, filer and mptt. When in production, thumbnails generated by easy_thumbnails are showing correctly, other than the fact that these are greyscale and pixelated. When I "Open original image in new tab" on Chrome, the image linked is also greyscale and pixelated. Strangely, this only happens with PNG but not with JPG images. Following is how I loaded the thumbnail tag and specified source, size and option (i.e. crop). {% load thumbnail %} <img src="{% thumbnail object.profile_picture 300x300 crop %}" alt="" class="img activator card-profile-image" width="100%"> I have ruled out the possibility that the server user does not have access to the media file because the image shows up correctly (full-colored) when loaded without using easy_thumbnails as shown below: <img src="{{ user.MemberProfile.profile_picture.url }}" alt="" height="20%" width="auto"> Any pointer on how to debug this would be really helpful. -
viewsets not working with ^ and $ added and invalid literal for int() with base 10: on string regex django rest framework
I have the following urls which are directed towards viewsets in djangorestframework router.register(r'city-list', CityListViewSet, base_name='city-list') as is above this url works but if I do this: router.register(r'^city-list$', CityListViewSet, base_name='city-list') it breaks and I get a 404 error. the ^ is a regex expression for pattern matching from the beginning, the $ is like the ^ but for pattern matching in the back. As well, check out this url: router.register(r'venue-filter-options-list/(?P<city>[a-zA-Z]+)' Having the same problem with ^ and $ I am getting an error when I input a string into the city placeholder if I put for example chicago into the city placeholder when calling the url in the browser I get the following error in the django debug page: Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'chicago' that doesn't make any sense my regex is correct. Anyone else have this issue? -
Django Fixtures Deserialization Error: No JSON object could be decoded
I am trying to call python manage.py loaddata fixture_20170717.json but I get the following error: File "C:\Users\Anon\Anaconda2\lib\json\decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") django.core.serializers.base.DeserializationError: Problem installing fixture 'D:\resi_django\viewer_django\topology_viewer\viewer\fixtures\fixture_20170717.json': No JSON object could be decoded The "fixture_20170717.json" file looks like this: [ { "model": "viewer.net", "pk": 1, "fields": { "net_name": "Aarnet-tz", "data": { "graph_data": { "nodes": ["Perth1", "Sydney2", "Sydney1", "Armidale", "Brisbane1", "Brisbane2", "Darwin", "Adelaide1", "Adelaide2", "Rockhampton", "Alice,Springs", "Cairns", "Melbourne1", "Canberra2", "Canberra1", "Melbourne2", "Hobart", "Perth2", "Townsville"], "links": [["Perth1", "Adelaide1"], ["Perth1", "Perth2"], ["Sydney2", "Brisbane2"], ["Sydney2", "Armidale"], ["Sydney2", "Sydney1"], ["Sydney2", "Melbourne2"], ["Sydney1", "Brisbane1"], ["Sydney1", "Canberra2"], ["Brisbane1", "Brisbane2"], ["Brisbane1", "Rockhampton"], ["Darwin", "Adelaide1"], ["Darwin", "Alice,Springs"], ["Adelaide1", "Melbourne1"], ["Adelaide1", "Adelaide2"], ["Adelaide2", "Melbourne2"], ["Adelaide2", "Alice,Springs"], ["Adelaide2", "Perth2"], ["Rockhampton", "Townsville"], ["Cairns", "Townsville"], ["Melbourne1", "Hobart"], ["Melbourne1", "Canberra1"], ["Melbourne1", "Melbourne2"], ["Canberra2", "Canberra1"], ["Melbourne2", "Hobart"]] }, "city_data": { "Perth1": { "lat": -31.93333, "long": 115.83333 }, "Sydney2": { "lat": -33.86785, "long": 151.20732 }, "Sydney1": { "lat": -33.86785, "long": 151.20732 }, "Armidale": { "lat": -30.51667, "long": 151.65 }, "Brisbane1": { "lat": -27.46794, "long": 153.02809 }, "Brisbane2": { "lat": -27.46794, "long": 153.02809 }, "Darwin": { "lat": -12.46113, "long": 130.84185 }, "Adelaide1": { "lat": -34.93333, "long": 138.6 }, "Adelaide2": { "lat": -34.93333, "long": 138.6 }, "Rockhampton": { "lat": -23.38333, "long": 150.5 … -
Dynamic select dropdown
I want to build dynamic select boxes for Country and States, Based on selection of Country States dropdown should updated, I have modelled for Country and State. When I select the country, I want to get the states which belong to that country from the model. I found this link, but using forms doesn't suite to my scenario. Is there solution to tackle this problem using ajax and Django? This link has solution in rails. Is there any option like this in Django? -
Naming a JSON Array in Django REST API
I've seen some of the similar questions on this subject, but the structure of other posters' code is different than the tutorial I followed for building the REST api (http://www.django-rest-framework.org/tutorial/quickstart/). Following the tutorial, I get an unnamed JSON response when querying the API. I have serializers.py and views.py as the two files that process the JSON: serializers.py: from rest_framework import serializers from main.models import Request class RequestSerializer(serializers.ModelSerializer): class Meta: model = Request fields = ('user', 'request', 'time') views.py class RequestViewSet(viewsets.ModelViewSet): queryset = Request.objects.all().order_by('-time') serializer_class = RequestSerializer paginate_by = None Other solutions have been along the lines of adding return Response({"data": serializer.data}), but I'm unsure where I could add this in my code. -
Get difference of foreign key attribute with django
I'm trying to get a queryset where a Task has two Issuances which have been created within 10 seconds of one another. Models are as follows: Class Task(models.Model): # stuff Class Issuance(models.Model): task = models.ForeignKey(Task, blank=True, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(default=timezone.now) What I've got so far: qs = ( Task.objects .annotate(count=Count('issuance')) .filter(count__gt=1, count__lte=2) .annotate(time_difference=F('issuance__created')) # Need to fix this .annotate( dupe=Case( When( time_difference__lt=10, # Less than 10 seconds then=Value(1), ), default=Value(0), output=BooleanField(), ) ) ) I think I'm pretty close but I need some way to calculate the time difference between the creation date of the two issuances for any one Task. Also, need to do a comparison that the time delta is less than 10 seconds; not sure if what I have will work. Can anyone help, please? -
every request from a django app increasing mysql number of connections
I have a project built using django 1.11 and i am sending a request from my admin view and it is creating a new DB connection on every request(using django development server, runserver). But the same thing using gunicorn as server does not increase the number of connections in DB it uses same connection that was created in first request. In my database settings CONN_MAX_AGE is set to 300 which is 5mins. I am sending second request within 5 mins, so it is supposed to use same connection that was created in first request. Any idea why, with runserver, django is creating new DB connection on every request and not following persistent connections behavior of django ? -
Importing data from postgres and integrating Google maps API in Django
I am new to Django. I have a django code for a website in its initial phase, and planning to import huge csv(s) data into postgres database, and further using that data to print on google map API as trajectories using different colors (like a heatmap). My CSV dataset consists of a trajectory path (latitude and longitude) with other variables which show traffic density on that path. so basically I want to add a layer to Google maps API with my own traffic data. There are many tutorials on google maps API and traffic layers, but I can not find any specific tutorials for using google maps integration using Django and inporting the data from postgres database. Will I need javascript to do it? Any help would be greatly appreciated. I want to do something like this on my web page, I edited the image just for example -
Template not found Exception while trying to use jinja templates in django
I'm using django and made an app through it, I want to use jinja templates and hence made jinja2.py file and stored it in the main app folder, also I made required changes in settings.py , here are the corresponding files : mysite/setting.py : """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.3. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'm$)4%$*9t01g+1ak+_65f@vo%f-2^9#h6tnhn%2g@wke+)ssm0' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'webEs', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath('C:/Users/kanika_kapish/Desktop/mysite/webEs'))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(PROJECT_PATH, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'environment': "webEs.jinja2.environment", }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { … -
Better way to check if a object is present in Django ORM among Get/Filter?
Lets consider I am trying to find if a user with primary key 20 exists or not? I can do this in 2 ways. The First one : try: user = User.objects.get(pk=20) except User.DoesNotExist: handle_non_existent_user() The other way could be : users = User.objects.filter(pk=20) if not users.exists(): handle_non_existent_user() Which is better method to do check existence? This might be related to this : What is the best way to check if data is present in django? However, people favoured the first method because of specified examples did not had the reference of model queryset. -
Django - Send bulk email using send_mass_mail()
I tried to send mass email using loop and it worked. However, the entire process takes long duration to complete with increase in the number of recipients. So I decided to send email using send_mass_email(). Unfortunately my code dont seem to work. Nor am I able to find the problem. Please help. view: def noticeboard(request): title = "Notice Board" emaillists = [] given_value = request.POST.get('radioGroup') if given_value == 'All': emaillist = MyUser.objects.all().values_list('email', flat=True) for email in emaillist: emaillists.append(str(email.encode('utf8'))) if given_value == 'XYZ': ..... ..... form = noticeboardForm(request.POST or None) if form.is_valid(): FROM = "noticeboard@gmail.com" SUBJECT = form.cleaned_data.get('subject').decode('utf-8') TEXT = form.cleaned_data.get('body').decode('utf-8') message = (SUBJECT, TEXT, FROM, emaillist) try: connection = get_connection() connection.open() send_mass_mail(message, fail_silently=False) connection.close() print('successfully sent the mail') except: print("failed to send mail") return redirect('delivery_success') return render(request, "noticeboardform.html", {"form": form, "title": title}) def delivery_success(request): return render(request, 'delivery_success.html') -
load static file in a template that extends other template - Django javascript
I want to load a javascript file in the template that extends my base_generic template. I am using generic listView to render the template. Since I can not use "{% url %}" tamplate tag inside of "{% block %}" tag I hardcoded the link as follows: <script src="static/js/search.js"> Unfortunately the file does not work and I get a a message that: "SyntaxError: expected expression, got '<' " I guess it is because my view tries to render the template as html (am I right?) - my assumption is based on this post: SyntaxError: expected expression, got '<' So my question is: how can I load a static file in the template that extends another template. -
Django AbstractBaseUser vs BaseUserManager when creating custom user
I have a django application with specific fields, so i decided to create a new user model. I was following the documentation thoroughly, but i could not wrap my head around extending AbstractBaseUser and BaseUserManager from here. 1) Why would i need to extend two classes to create a single user model. I want to know if the fields we specify in classes anyway similar. 2) Is there any similarities between those email fields specified here in MyUserManager and MyUser or both are same? 3) In my app i want to use mobile number(Charfield max_length=12) as login neither email or nor username 4) Django provided how to create a custom user model with email then i have another specific question do i need to specify mobile field in create_user and create_superuser and AbstractBaseUser model as well. If you provide an excerpt with mobile number as USERNAME_FIELD that would be very helpful. I know these are basic django questions but if you want to create a custom user model you might come across these questions several times -
Any idea to using django to retrieve data from web?
Any idea to using Django that retrieve data from a portal? Can anyone share me some idea? Below code are not runable: import urllib.request from bs4 import BeautifulSoup def index(): url = "https://www.google.com.sg" response = urllib.request.urlopen(url) content = response.read() soup = BeautifulSoup(content, 'lxml') return soup s = index() print(s) Can anyone help me on this? -
mysql table do not has primary key, django orm can not use
i use django orm to op my mysql table, but i have some data table where they do not has primary key, it has throw exception like this: django.db.utils.OperationalError: (1054, "Unknown column 'XXX.id' in 'field list'"), what can i do to fix the exception and do not modify my table schema?